angularangular-materialmd-select

How to select value in md-select with formcontrolname in angular 4


I am using react form and angular material's md-select .

This is my form

<md-select placeholder="Parent Category" class="full-width" formControlName="parent_id">
  <md-option>None</md-option>
  <md-option *ngFor="let category of plainCategories" [value]="category.id">
    <span *ngIf="category.subcategory.length==0">&nbsp;</span>{{ category.name }}
  </md-option>
</md-select>

I want to set md-select value from code and this is what i have tried

onClicked(e){
  if (e && e.action == 'edit') {

    let item = {
      id: e.item.id,
      name: e.item.name,
      slug: e.item.slug,
      parent_id: e.item.parent_id
    };

    this.categoryForm.setValue(item);
  }
} 

This is updating the form value ({{categoryForm.val | json}} shows the value set) but the select option is not showing the option as selected. How can i select the md-option?

enter image description here


Solution

  • if set of fields to be updated is not full as declared in the form (for example if there is also element called category, besides id, name, slug and parent_id), then setValue() will not work, use patchValue() instead:

    this.categoryForm.patchValue(item);
    

    you also can set value per field:

    this.categoryForm.get('parent_id').setValue(e.item.parent_id);
    

    see my example plunker: https://plnkr.co/edit/PftFkCQ5fvLICczt7gAO?p=preview