Task Management

ApexGantt exposes a programmatic CRUD API for adding, updating, deleting, and re-parenting tasks after the chart has rendered. Every mutation method is recorded in the undo history, so users can reverse any change without extra wiring on your part.


Adding tasks

Use addTask(input, options?) to insert a new task and trigger a re-render.

const gantt = new ApexGantt(document.querySelector('#chart'), {
  inputDateFormat: 'YYYY-MM-DD', // the dates on this page are ISO
  series: [],
})
gantt.render()

// Add a top-level task
gantt.addTask({
  id: 'review',
  name: 'Review',
  startTime: '2024-08-01',
  endTime: '2024-08-05'
})

To place a task inside an existing parent, pass its id in the second argument:

// Insert as a child of an existing task
gantt.addTask(
  {
    id: 'sub-1',
    name: 'Subtask',
    startTime: '2024-08-01',
    endTime: '2024-08-03'
  },
  { parentId: 'review-phase' }
)

What to expect:

  • The method returns the inserted Task object on success.
  • It returns null if a beforeTaskAdd lifecycle hook cancelled the insertion.
  • It throws if id is missing or already exists in the chart. Since 3.20.0 a throwing addTask leaves the previous data in place.
  • Dates are parsed with inputDateFormat, like the initial series.
  • A task added under a parent starts one level below it.
  • The parent can also come from input.parentId. Since 3.20.0 beforeTaskAdd and taskAdded report the parent the task lands under: the parentId option, else input.parentId, and undefined for an id that matches no task (the task is then added at the root). Before, input.parentId was ignored by both, so a hook that checked the parent was bypassed and taskAdded reported a root task.

Updating tasks

Use updateTask(taskId, updatedTask) to apply a partial update to an existing task. You only need to supply the fields you want to change; everything else is left untouched.

// Mark a task as complete
gantt.updateTask('task-3', { progress: 100 })

// Shift the scheduled dates
gantt.updateTask('task-3', { startTime: '2024-09-01', endTime: '2024-09-15' })

// Rename the task
gantt.updateTask('task-3', { name: 'Final Review' })

The chart updates the relevant rows without performing a full re-render, so the operation is efficient even for large task trees. The change runs through beforeTaskUpdate and is recorded in the undo history.

updateTask throws if the taskId does not match any task in the current dataset, or if the result fails validation (after firing taskUpdateError). Validate the id before calling if the source is dynamic. Since 3.20.0 a throwing call leaves the previous data in place, and the second argument is typed Partial<TaskInput>, so { type: 'milestone' } compiles.

Since 3.20.0 an edit keeps the task's tree level: getTask(id).level, taskUpdateSuccess.updatedTask.level, the row indent and aria-level stay right after later renders such as update({ theme }) or a collapse. Before, an edited nested task could drop back to the top level.

Since 3.20.0 updateTask emits taskUpdate and taskUpdateSuccess with source: 'api', like every other edit path. Pass { silent: true } as a third argument to suppress them, for example when applying a change that came from your server, so your save handler does not send it back:

socket.on('task-changed', ({ id, changes }) => {
  gantt.updateTask(id, changes, { silent: true })
})

Before 3.20.0 updateTask emitted no events. Since 3.20.0 it also stores changes for tasks whose rows are not rendered (under a collapsed parent, filtered out, or outside the virtualized window); earlier versions dropped those changes.

Reading tasks

Since 3.20.0, getTask(id) returns a copy of a task with its current values (edits included), or null for an unknown id. getTasks() returns every task, including collapsed and filtered-out ones, in tree order. The copies include baseline, segments, assignees and an object dependency, so changing a returned task never changes the chart; custom fields you added are copied by reference.

const task = gantt.getTask('task-3')   // { id, name, startTime, endTime, progress, ... } or null
const all = gantt.getTasks()
const links = gantt.getDependencies()  // every link as it is now

A task's dependency holds only the link it was loaded with, so links added with addDependency() or drawn by the user are not in getTasks(). To save the plan, save getDependencies() (3.20.0+, returns DependencyLink objects { fromId, toId, type, lag }) with the tasks and re-add the links after loading; the Methods reference shows the reload code. On earlier versions, record links from the dependencyAdded and dependencyRemoved events instead.

To open or close a parent row from code, use expandTask(id) and collapseTask(id) (3.20.0+). They change view state only and are not recorded in undo history.


Deleting tasks

Use deleteTask(taskId, options?) to remove a task and re-render.

// Remove a leaf task (no children)
gantt.deleteTask('task-5')

The method returns true when the task is removed, or false when a beforeTaskDelete hook cancelled the operation.

Cascade modes

When a task has children, you must decide what happens to them. Pass a cascade option to control this.

ModeBehaviorWhen to use
'forbid' (default)Throws if the task has childrenPrevents accidental bulk deletion
'children'Deletes the task and all its descendants in one undoable transactionRemoving an entire phase or subtree
'orphan'Moves the task's immediate children up to the deleted task's parent (or root), then removes the taskFlattening a hierarchy without losing work
// Remove a parent and all its descendants
gantt.deleteTask('phase-1', { cascade: 'children' })

// Remove a parent but keep its children (they move up one level)
gantt.deleteTask('phase-1', { cascade: 'orphan' })

Any dependency edges that referenced the deleted task are removed in the same transaction. You do not need to clean up arrows manually.


Moving tasks (re-parenting)

Use moveTask(taskId, options?) to change a task's parent without altering its other properties.

// Move task-5 under a different phase
gantt.moveTask('task-5', { newParentId: 'phase-2' })

// Promote task-5 to the root level
gantt.moveTask('task-5', { newParentId: null })

Pass newParentId: null to move a task to the root of the hierarchy.

The operation is recorded in the undo history. If the move would create a cycle (for example, moving a parent into one of its own descendants), moveTask throws rather than producing an invalid tree. The moved subtree takes its new depth (indent, level and aria-level).


Milestones

Set type: 'milestone' on a task to render it as a diamond on the timeline instead of a bar. Milestones represent a point in time rather than a duration: endTime is optional and the diamond sits on startTime. Since 3.20.0 a task with no endTime, no type and no children is also drawn as a milestone (an explicit type: 'task' without endTime still throws), and TypeScript accepts the plain string 'milestone'; earlier versions need TaskType.Milestone in typed code.

Since 3.20.0 a parent row does not need full dates of its own:

  • A parent with a startTime, no endTime and no type is a 'task' drawn as a summary bar spanning its children.
  • A parent with only an endTime, or with no dates at all, is drawn as a summary bar over its children. Earlier versions threw Task must have an id, start, and end date for an end-only parent.
  • A task with no startTime and no children throws Task "<id>" has no startTime and no children. Provide dates or add child tasks. This covers an end-only leaf and a type: 'milestone' task with no start, which used to throw a different message.
gantt.addTask({
  id: 'go-live',
  name: 'Go Live',
  type: 'milestone',
  startTime: '2024-09-30',
  endTime: '2024-09-30'
})

The two task type values are:

  • 'task' (default): a standard bar spanning the duration.
  • 'milestone': a diamond rendered at a single date.

There is no 'summary' type. A task with children is drawn as a summary bar automatically (its showSummaryBar defaults to true), spanning its children; set showSummaryBar: false on a parent to draw its own dates instead.

You can also update an existing task's type:

gantt.updateTask('go-live', { type: 'milestone' })

Drawing tasks on the timeline

With enableDrawTask: true, users can create a task by dragging across an empty part of the timeline. On release a task is created with the swept date range snapped to snapUnit / snapValue. A preview bar follows the cursor, a plain click creates nothing, and Escape cancels mid-drag (since 3.20.0 wherever focus is; earlier versions only when focus was inside the chart). Existing bars stay draggable and resizable, since the draw gesture only starts on empty space.

const gantt = new ApexGantt(el, {
  series: tasks,
  enableDrawTask: true,
  snapUnit: 'day',
})

Off by default, so existing charts are unaffected. Creation flows through the same beforeTaskAdd veto hook as every other add, so it is undoable and emits a taskAdded event.

Splitting tasks

A task can be split into several worked segments separated by gaps on a single row. See the Split Tasks guide for the segments data shape and the splitTask() / isSplit() methods.

Lifecycle hooks

Lifecycle hooks let you validate or cancel CRUD operations before they take effect. Register them in the GanttUserOptions when you construct the chart.

const gantt = new ApexGantt(document.querySelector('#chart'), {
  series: tasks,

  beforeTaskAdd: ({ input, parentId }) => {
    // Reject tasks without a name
    if (!input.name || input.name.trim() === '') {
      alert('A task must have a name.')
      return false
    }
  },

  beforeTaskDelete: ({ task }) => {
    // Ask the user before deleting an in-progress task
    if (task.progress > 0 && task.progress < 100) {
      return confirm(`"${task.name}" is still in progress. Delete anyway?`)
    }
  },

  beforeTaskUpdate: ({ task, updates }) => {
    // Reject out-of-range progress values
    if (updates.progress !== undefined && updates.progress > 100) {
      return false
    }
  },

  beforeTaskMove: ({ task, oldParentId, newParentId }) => {
    // Prevent moving tasks into a locked phase
    if (lockedPhaseIds.has(newParentId)) {
      return false
    }
  }
})

How hooks work:

  • Return false to cancel the operation. The chart state does not change and nothing is written to the undo history.
  • Return true, undefined, or anything other than false to allow the operation to proceed.
  • Hooks are synchronous. A returned Promise is not awaited and does not cancel anything, so make the decision synchronously (for example with confirm(), or by checking state you already hold).

Each hook receives one context object:

HookContext
beforeTaskAdd{ input, parentId }: the TaskInput about to be added and its parent id
beforeTaskUpdate{ task, updates }: the task as it is now and the partial update
beforeTaskDelete{ task, descendantIds, cascade }
beforeTaskMove{ task, oldParentId, newParentId } (a parent id is undefined at the root)
beforeDependencyChange{ change, fromId, toId, type, lag }, where change is 'add' or 'remove'

beforeTaskUpdate runs for every edit path since 3.20.0 (drag, resize, progress drag, dialog, inline edit, keyboard, updateTask()); before 3.20.0 only updateTask() and inline edits ran it.

When a parent is dragged or moved with the keyboard, the hook is asked about the parent and then about each child that moves with it. Since 3.20.0 vetoing one child keeps only that child in place: the hook is still asked about the later siblings and they move. Vetoing the parent skips all its children. Before, a child veto skipped every later sibling without asking the hook, and taskDragged.affectedChildTasks left them out. Descendants with no startTime (undated summary rows) are not edited by a parent drag, so they get no update events.

A parent drag or keyboard move commits the bar and its descendants as one batch. Each task still gets beforeTaskUpdate, taskUpdate, taskUpdateSuccess and a history entry (merged into one undo step), but since 3.20.0 all of the gesture's taskUpdate events fire first and its taskUpdateSuccess events follow, after the data is rebuilt. Code that expected each task's taskUpdate and taskUpdateSuccess to arrive as a pair should not rely on that order.


Selection API

ApexGantt includes a selection API for reading and controlling which tasks are highlighted. Enable it with the enableSelection option:

const gantt = new ApexGantt(document.querySelector('#chart'), {
  series: tasks,
  enableSelection: true
})
gantt.render()

Then use these methods at any point after rendering:

// Read the currently selected tasks (full Task objects)
const selected = gantt.getSelectedTasks()
console.log(selected.map((task) => task.id)) // ['task-1', 'task-3']

// Programmatically select specific tasks
gantt.setSelectedTasks(['task-1', 'task-3'])

// Clear all selections
gantt.clearSelection()

Without enableSelection: true these methods do nothing; since 3.20.0 they log a one-time console warning instead of failing silently.

setSelectedTasks is useful when you want to sync the chart's selection with an external list or table. For example, if a user clicks a task name in a sidebar, call setSelectedTasks with that id to highlight the corresponding row in the chart.