使用 Angular Gantt 的快速入门
本快速入门使用一个独立的 Angular 应用和官方包装包。它在一个专用的 Angular 组件中创建 Gantt,并将该组件挂载到 AppComponent 中,因此示例保持简洁,同时更贴近实际应用结构。
1. 创建一个 Angular 项目
创建一个独立的 Angular 应用(Angular CLI):
ng new angular-gantt-quick-start --standalone --routing=false --style=css
cd angular-gantt-quick-start
如果尚未安装 Angular CLI,请先安装(npm install -g @angular/cli)。
2. 安装 Angular Gantt
按照 Angular Gantt 安装指南 中的说明安装 React Gantt。
在本教程中我们使用评估包:
npm install @dhtmlx/trial-angular-gantt
或
yarn add @dhtmlx/trial-angular-gantt
如果你已经使用 Professional 包,请在命令和导入中把 @dhtmlx/trial-angular-gantt 替换为 @dhx/angular-gantt。
3. 添加全局样式
打开 src/styles.css 并添加 Gantt 样式:
src/styles.css
@import "@dhtmlx/trial-angular-gantt/dist/angular-gantt.css";
html,
body {
height: 100%;
margin: 0;
}
app-root {
display: block;
height: 100vh;
}
此次快速入门使用全局 CSS 导入(src/styles.css),因此在 AppComponent 中不需要 ViewEncapsulation.None。
如果你以后将 Gantt CSS 导入(或对内部 Gantt 类如 .dhx-gantt-root 的覆盖)移动到某个组件样式表中,Angular 的默认样式封装可能会将这些选择器进行作用域化。在这种情况下,请在该组件上设置 encapsulation: ViewEncapsulation.None,或将样式保持全局。
4. 添加 Demo 数据
创建 src/app/demo-data.ts。
包装器导出 SerializedTask 和 SerializedLink - 它们是放在甘特外部的任务/链接数据的推荐类型。日期可以是字符串或 Date 对象。
import type { SerializedTask, SerializedLink } from '@dhtmlx/trial-angular-gantt';
export const tasks: SerializedTask[] = [
{
id: 1,
text: 'Office itinerancy',
type: 'project',
start_date: new Date(2026, 1, 2).toISOString(),
duration: 10,
progress: 0.4,
open: true,
parent: 0,
},
{
id: 2,
text: 'Planning',
start_date: new Date(2026, 1, 2).toISOString(),
duration: 4,
progress: 0.6,
parent: 1,
},
{
id: 3,
text: 'Implementation',
start_date: new Date(2026, 1, 6).toISOString(),
duration: 5,
progress: 0.2,
parent: 1,
},
];
export const links: SerializedLink[] = [{ id: 1, source: 2, target: 3, type: '0' }];
5. 创建一个 Gantt 组件
创建 src/app/gantt-chart.component.ts:
src/app/gantt-chart.component.ts
import { Component } from '@angular/core';
import {
DhxGanttComponent,
type AngularGanttDataConfig,
} from '@dhtmlx/trial-angular-gantt';
import { links, tasks } from './demo-data';
@Component({
selector: 'app-gantt-chart',
standalone: true,
imports: [DhxGanttComponent],
host: { style: 'display:block;height:100%;' },
template: `
<dhx-gantt
style={{display: 'block', height: '100%'}}
[tasks]="tasks"
[links]="links"
[config]="config"
[data]="dataConfig">
</dhx-gantt>
`,
})
export class GanttChartComponent {
tasks = tasks;
links = links;
config = {
columns: [
{ name: 'text', tree: true, width: '*' },
{ name: 'start_date', label: 'Start', align: 'center' },
{ name: 'duration', label: 'Duration', align: 'center' },
{ name: 'add', width: 44 },
],
};
dataConfig: AngularGanttDataConfig = {
save: (entity, action, item, id) => {
console.log('save', { entity, action, item, id });
},
};
}