<mat-form-field appearance="fill">
<mat-label>Favorite food</mat-label>
<mat-select [formControl]="topFormControl" [(value)]="topSelectValue">
<mat-option *ngFor="let food of foods" [value]="food" >
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
ngOnInit(): void {
this.topFormControl.valueChanges
.pipe(
startWith(this.topFormControl.value),
pairwise()
).subscribe(
([old, cur]) => {
if(
//cur.value === 's'
){
//prevent user select the option, force mat-select still shows the old option.
}
}
);
}
foods: Food[] = [
{ value: 's', viewValue: 'Steak' },
{ value: 'p', viewValue: 'Pizza' },
{ value: 't', viewValue: 'Tacos' },
];
Is there any solution when user select Steak in Favorite food, prevent mat-select to show Steak but keep the old option?
Thanks a lot.
CodePudding user response:
You can use setValue method on FormControl and pass emitEvent:false
as second argument to stop triggering valueChanges again.
ngOnInit(): void {
this.topFormControl.valueChanges
.pipe(
startWith(this.topFormControl.value),
pairwise()
).subscribe(
([old, cur]) => {
if(
//cur.value === 's'
){
this.topFormControl.setValue(curr.value,{emitEvent:false})
}
}
);
}