如何 select md-select 中的值与 angular 中的 formcontrolname 4

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

我正在使用反应形式和 angular material 的 md-select .

这是我的表格

<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>

我想从代码中设置 md-select 值,这是我尝试过的

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);
  }
} 

这正在更新表单值({{categoryForm.val | json}} 显示值集)但 select 选项未将选项显示为 selected。我如何 select md 选项?

如果要更新的字段集不完整(例如,除了 idname、[= 之外还有名为 category 的元素15=] 和 parent_id),那么 setValue() 将不起作用,请改用 patchValue()

this.categoryForm.patchValue(item);

您还可以为每个字段设置值:

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

查看我的例子 plunker:https://plnkr.co/edit/PftFkCQ5fvLICczt7gAO?p=preview