when i check the checkbox
i am getting undefined
when i uncheck getting the value of what i previously checked. how to fix this issue?
<div *ngSwitchCase="'multiselect'" [ngClass]="{'mandate': field.required}" >
<mat-form-field appearance="outline" >
<mat-label>{{field.placeHolder}}</mat-label>
<mat-select [formControlName]="field.controlName" multiple [(ngModel)]="countrySelected" >
<mat-option *ngFor="let option of field.options" [value]="option"
(onSelectionChange)="countriesUpdate($event)">
{{option.label}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
console.log(this.countrySelected);
undefined
on check
how to get current value?
CodePudding user response:
onSelectionChange is triggered before the form value is set, so you will get the last set value, there are two ways you can resolve this problem
- Listen to selectionChange on mat-select instead of onSelectionChange on mat-option
- Subscribe to the form control value changes event
<mat-select
[formControlName]="field.controlName"
multiple
[(ngModel)]="countrySelected"
(selectionChange)="countriesUpdate($event)"
>
<mat-option *ngFor="let option of field.options" [value]="option.label">
{{ option.label }}
</mat-option>
</mat-select>
ngOnInit() {
this.formGroup
.get('formControlName')
.valueChanges.subscribe((selectValue) => console.log(selectValue));
}