组件加载时如何在角度垫选择中设置值? [英] How to set value in angular mat-select when component loading?

查看:58
本文介绍了组件加载时如何在角度垫选择中设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了角材料(" @ angular/material":"7.1.0 ")垫选择框,然后我使用了窗体控件而不是ng模型,现在的问题是我可以t在加载组件时设置值.我需要从列表中将第一个值设置为mat-select框,我尝试过但不能这样做.

I used angular material("@angular/material": "7.1.0") mat-select box and then i used form control instead of ng model, now the problem is i can't set the value when the component is loading. I need to set the first value to mat-select box from the list, i tried but i cant do that.

我已经在stackblitz上创建了一个代码,这里是链接: https://stackblitz.com/编辑/angular-zt1a9f

I have created a code at stackblitz, here is the link: https://stackblitz.com/edit/angular-zt1a9f

请帮助我.

推荐答案

使用compareWith通过比较功能内部的名称来选择默认值.另请注意,我已将value绑定更改为[(value)] ="animal".并删除了selectedValue.您可以通过在formControl中分配默认值来选择默认值,然后在组件中查看以下更改.

Use compareWith to select the default value by comparing the name inside the compare function. Also note, I've changed value binding to [(value)] ="animal". And removed selectedValue. You select the default by assigning it in the formControl, look below changes in the component.

<form [formGroup]="myGroup">
<mat-form-field>
  <mat-select placeholder="Favorite animal" [compareWith]="compareThem" formControlName="animalControl" required >
    <mat-option>--</mat-option>
    <mat-option *ngFor="let animal of animals" [(value)] ="animal"  >
      {{animal.name}}
    </mat-option>
  </mat-select>
</mat-form-field>
</form>

在您的组件中,添加:

export class AppComponent  {

  animals = [
    {name: 'Dog', sound: 'Woof!'},
    {name: 'Cat', sound: 'Meow!'},
    {name: 'Cow', sound: 'Moo!'},
    {name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
  ];  

  myGroup = new FormGroup({
      animalControl: new FormControl(this.animals[1], [Validators.required]) //I'm assigining Cat by using this.animals[1], you can put any value you like as default.
  });


  compareThem(o1, o2): boolean{
    console.log('compare with');
    return o1.name === o2.name;
  }
}

这篇关于组件加载时如何在角度垫选择中设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆