如何在角度4中使用formcontrolname在md-select中选择值

如何在角度4中使用formcontrolname在md-select中选择值

问题描述:

我正在使用反应窗体和角度材质的md-select。如何在角度4中使用formcontrolname在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-选择价值,这是我曾尝试

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}}显示值设置),但选择选项没有显示选项。我如何选择md选项?

enter image description here

如果设置字段进行更新不完全的形式声明(例如,如果还有元素称为category,除了idnameslugparent_id),然后setValue()将无法​​正常工作使用patchValue()代替:

this.categoryForm.patchValue(item); 

你也可以每场设定值

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

+0

感谢您的回答。当值是字符串时,这在plnkr中是完美的。但我的parent_id是数字这就是为什么没有选择md选项。我怎样才能让数字可选? –

+1

更新了我的plunker,widh数字ID,如果需要,它也可以与复杂对象一起使用。如果你需要进一步的帮助,请更新我的蹦床,我会尽力帮忙 – Andriy