recently I'm trying to create a custom dropdown component using value accessor but I can't set a value to this dropdown.
This part of the dropdown component
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
ts part
@Input() foods:any
get value(): any {
return this.innerValue;
}
// set accessor including call the onchange callback
set value(v: any) {
console.log(v, "v");
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
App Component HTML:
<app-input-dropdown [foods]="foods" formControlName="dropdown">
</app-input-dropdown>
ts :
this.foods = [
{ value: "steak-0", viewValue: "Steak" },
{ value: "pizza-1", viewValue: "Pizza" },
{ value: "tacos-2", viewValue: "Tacos" }
];
ngOnInit() {
this.myForm = this.fb.group({
dropdown:[null]
})
const valueToSet = { value: "steak-0", viewValue: "Steak" }
this.myForm.dropdown.patchValue({
dropdown:valueToSet
}) ;
}
So this is not working, I don't know why.