I'm currently developing a "Tasks" application using Angular 9 and PHP. I've encountered an error that says
Cannot find control with name: <control name>
when attempting to pre-fill the update form with data.
Here is the form template:
<form [formGroup]="updateTask" name="edit_task_form">
<mat-form-field appearance="standard">
<mat-label>Title</mat-label>
<input matInput placeholder="Title" formControlName="title" placeholder="Title">
</mat-form-field>
<mat-form-field appearance="standard">
<mat-label>Short Description</mat-label>
<input matInput placeholder="Short description" formControlName="short-description" placeholder="Short Description">
</mat-form-field>
<mat-form-field>
<mat-label>Category</mat-label>
<mat-select formControlName="tags">
<mat-option *ngFor="let category of categories" [value]="category.id">{{category.name | titlecase}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="standard">
<mat-label>Full Description</mat-label>
<textarea matInput formControlName="full-description" placeholder="Full Description"></textarea>
</mat-form-field>
<div class="text-center">
<button mat-flat-button type="submit" color="accent" [disabled]="updateTask.pristine || updateTask.invalid">Update</button>
</div>
</form>
In the component's .ts file:
task_hash: string;
currentTask: any = {};
constructor(private _apiService: ApiService, private _formBuilder: FormBuilder, private _sharedService: SharedService) {}
updateTask = this._formBuilder.group({});
ngOnInit(): void {
this.task_hash = this._apiService.task_hash;
this._apiService.getTaskInfo().subscribe(res => {
this.currentTask = res;
const formInfo = this.currentTask.info;
formInfo.forEach(item => {
if (item.key === 'title' || item.key === 'short-description' || item.key === 'description' || item.key === 'tags') {
this.updateTask.addControl(item.key, this._formBuilder.control(item.data, item.key !== 'tags' ? Validators.required : null));
};
});
});
}
The browser console shows an error message (for each form field):
Cannot find control with name: 'title'
.
The issue seems to stem from the fact that in another component, I open the form within an Angular Material Dialog triggered by a button click:
<button mat-button color="primary" (click)="openForm($event, task.task_hash)">Open</button>
In the trigger's .ts file
openEditForm(event, task_hash): void {
event.stopPropagation();
// Dialog Configuration
const dialogConfig = new MatDialogConfig();
dialogConfig.width = '60%';
// Open Dialog
this._matDialog.open(TaskFormComponent, dialogConfig);
// Pass test_hash to API Service
this.apiService.test_hash = test_hash;
}
To make the dialog work correctly, I also added this in the TaskModule:
entryComponents: [TestFormComponent];
It appears that the dialog opens before the form is populated, preventing the form from being filled. How can I resolve this issue?