I have a form that uses the Angular material mat-select and i get my data from and observable for the options and set the value of the selected item via code as well. All that works fine but what I am having an issue with is that i have code that only allows the update if the form is not pristine and its valid. So i was assuming that changing the value of the mat-select box would make pristine false but that's not the case.
Below is there code i use in the template , is there anything missing or do i have to use a onChange Event to manually set the form to pristine = false
<mat-form-field ngDefaultControl label=" " formControlName="parent">
<mat-label>Parent</mat-label>
<mat-select [(value)]="menuData.parent">
<mat-option value="" aria-selected="true" selected> --Select Parent -- </mat-option>
<mat-option *ngFor="let parent of menuParents$ | async" [value]="parent._id">
{{ parent.name}}
</mat-option>
</mat-select>
</mat-form-field>
I fixed this for now by using the selectionChange Event
<mat-select [(value)]="menuData.parent" (selectionChange)="selectionChange($event)">
selectionChange(e) {
console.log(e)
this.form.markAsDirty()
}
Even so this works i am not sure and certain this is the correct way to do this. I looked at the docs of mat-select but cant find anything on how to do this otherwise.
CodePudding user response:
You should not do this manually.
It looks like the problem is that you have set formControlName
on <mat-form-field>
rather than <mat-select>
.
formControlName
binds a control in the template to the form model, in this case you have bound it to the wrong control so changes to the select will not be recognised by the form system meaning no change to the forms validity.