【问题标题】:How to select value in md-select with formcontrolname in angular 4如何在角度 4 中使用 formcontrolname 在 md-select 中选择值
【发布时间】:2018-03-05 10:16:07
【问题描述】:

我正在使用反应形式和角度材料的 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}} 显示设置的值)但选择选项未显示已选择的选项。如何选择 md 选项?

【问题讨论】:

    标签: angular angular-material md-select


    【解决方案1】:

    如果要更新的字段集不完整,如表单中声明的​​(例如,除了idnameslugparent_id 之外,还有称为category 的元素),则setValue() 不起作用,请改用patchValue()

    this.categoryForm.patchValue(item);
    

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

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

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

    【讨论】:

    • 感谢您的回答。当值为字符串时,这在 plnkr 中非常有效。但是我的 parent_id 是数字,这就是未选择 md-option 的原因。我怎样才能使数字可选?
    • 更新了我的 plunker,宽数字 ID,如果需要,它也可以处理复杂的对象。如果您需要进一步的帮助,请更新我的 plunker,我会尽力提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2017-06-27
    • 1970-01-01
    • 2019-01-23
    • 2018-03-24
    • 1970-01-01
    • 2017-07-22
    相关资源
    最近更新 更多