When you click on “Edit Task” a form opens that already contains the values of a task.
This already works for simple strings, but not for values that have an array of values.
Problem:
- A task can be assigned to several people. However, the people who have already been assigned are not selected.
- The existing subTasks are also not displayed in the form.
I’ve already researched, but couldn’t implement the solution on my code:
patchValue on a FormArray object?
How to use FormArray in angular
Here just the relevant code:
export class TaskViewComponent {
protected readonly PRIORITIES = PRIORITIES;
protected readonly CATEGORIES = CATEGORIES;
protected readonly Object = Object;
taskForm!: FormGroup;
minDate!: Date;
keywords!: string[];
fromPopup = false;
@ViewChild(ChipFieldComponent) chipFieldComponent!: ChipFieldComponent;
contacts!: Contact[];
contactsSubscription!: Subscription;
constructor(private fb: FormBuilder, private taskService: TaskService, @Optional() @Inject(MAT_DIALOG_DATA) public data: { fromPopup: boolean, task: Task }, private contactService:ContactService) {}
ngOnInit() {
this.minDate = new Date();
this.fromPopup = !!this.data?.fromPopup;
this.keywords = [];
this.taskForm = new FormGroup({
title: new FormControl('', [Validators.required]),
dueTo: new FormControl('', [Validators.required]),
description: new FormControl(''),
priority: new FormControl('MEDIUM', [Validators.required]),
category: new FormControl(''),
assignedTo: this.fb.array([]),
subTasks: this.fb.array([]),
}
);
this.contactsSubscription = this.contactService.contacts$.subscribe(contacts => {
this.contacts = contacts;
})
if (this.data?.task) {
this.taskForm.setValue({
title: this.data.task.title,
dueTo: this.data.task.dueTo,
description: this.data.task.description,
priority: this.data.task.priority.key,
category: this.data.task.category.key,
assignedTo: this.data.task.contacts,
subTasks: this.data.task.subtasks
});
}
}
public get subTasksFormControl () {
return this.taskForm.get("subTasks") as FormControl;
}
}
HTML:
<div class="task-view-container">
<mat-dialog-content [ngStyle]="fromPopup ? {'padding-bottom': 0} : {}">
<form [formGroup]="taskForm" (ngSubmit)="onSubmit()" class="content-container mb-3">
<mat-form-field>
<mat-label>Assigned to</mat-label>
<mat-icon color="primary" matSuffix>group_add</mat-icon>
<mat-select formControlName="assignedTo" multiple>
@for (contact of contacts; track contact.id) {
<mat-option [value]="contact.id">{{ contact.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<app-chip-field [control]="subTasksFormControl" [controlTitle]="'subtask'"></app-chip-field>
</form>
</mat-dialog-content>
<mat-dialog-actions [ngClass]="{'from-popup': fromPopup, 'not-from-popup': !fromPopup}">
<button mat-raised-button color="primary" type="submit" [disabled]="!taskForm.valid">Create Task</button>
<button mat-raised-button type="button" color="warn" (click)="onReset()">Clear</button>
</mat-dialog-actions>
</div>