I have problem initializing a fromgroup with select multiple control. the initialization runs ok, but angular mark the from as invalid.
{{controlPanelForm.value | json}} -> tasks: ["3","1","5"]
{{controlPanelForm.status | json}} -> "INVALID"
now, when user select one or more tasks on multi-select the formgroup become valid.
{{controlPanelForm.value | json}} -> tasks: ["3","1","5"]
{{controlPanelForm.status | json}} -> "VALID"
I need, the formGroup valid from the initialization. thanks, in advance. ////html
<form [formGroup]="controlPanelForm" (ngSubmit)="submit()">
<select multiple id="tasks" size="7" [formControl]="controlPanelForm.get('tasks')">
<option *ngFor="let t of projectTasks" [ngValue]="t.id">{{t.title}}</option>
</select>
</form>
<div>
{{controlPanelForm.value | json}}
</div>
<div>
{{controlPanelForm.status | json}}
</div>
/////ts
controlPanelForm: FormGroup;
projectTasks: ProjectTask[] =[
{id:'3', title:'title3'},
{id:'1', title:'title1'},
{id:'5', title:'title5'},
]
projectTasksIds: string[];
ngOnInit() {
this.projectTasks.map((t) => {
this.projectTasksIds.push(t.id.toString());
});
this.buildForm();
}
buildForm(): void {
this.controlPanelForm = this.fb.group({
'tasks': [[this.projectTasksIds], Validators.compose([Validators.required, Validators.pattern('.+')])],
});
}
The problem was syncro! the values of tasks: ["3","1","5"] came from ajax. So, when the form initilize the values are: []. To solve problem, I used controlPanelForm.patchValues(...) method on ajax response. I hope this be helpfull for the others with the same problem.