'Mat-Option selected option based on patch value from api subscription
In my case i have several controls with mat-autocomplete with mat-options. in which the same form is handled for new entry creation and edit an existing entry data. So i have tried the following methods to implement the mat-option selected by default or mat-option is active based on the data fetched from the server side api, but the approach is not working. Please refer my code below provide a solution to make this case working.
HTML
<mat-form-field floatLabel="never" class="dropdown-arrow-icon">
<span class="material-icons">arrow_drop_down</span>
<input type="text" matInput formControlName="UOM" [matAutocomplete]="uomSelect" (keyup)="onUomKeyUp($event.target.value)">
<mat-autocomplete #uomSelect="matAutocomplete" [displayWith]="selectedDropdownForUom">
<mat-option *ngFor="let uom of uomOption" [value]="uom.value">
{{ uom.value }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
TYPESCRIPT
uomData = [
{ id: 1, value: "Parts", key: "PARTS" },
{ id: 2, value: "G/KG", key: "KG" },
{ id: 3, value: "L/Gal", key: "L" },
{ id: 4, value: "oz/lb", key: "OZ" },
{ id: 5, value: "%", key: "PERC" },
]
machineDetails;
ngOnInit(): void {
this.patchValue();
}
public selectedDropdownForUom = (uomData?: string): string => {
return uomData;
};
public onUomKeyUp(value: string): void {
if (value === "") {
// eslint-disable-next-line no-self-assign
this.uomOption = this.uomData;
} else {
this.uomOption = this.uomData.filter((item) => new RegExp(value, "gi").test(item.value));
}
}
private selectDefaultAutocompleteData(selectedUOM) {
find(this.uomSelect.options.toArray(), (uomOption) => uomOption.value === selectedUOM? .value)?.select();
}
public patchValue(){
this.httpClient.get("https://conversion.intil.io/units/45").subscribe(data =>
{this.machineDetails = data;
const selectedUOM = this.uomData.find(uom => uom.id === this.machineDetails.UoMID
this.experimentForm.patchValue({ UOM: selectedUOM.value});
this.selectDefaultAutocompleteData(selectedUOM);
})
}
RECIEVING OUTPUT actual output recieving
EXPECTED OUTPUT expected output
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
