angular - 如何在 Angular 5 中动态设置选定的下拉值

标签 angular typescript

我正在尝试在 Angular 5 中设置下拉列表的选定值。

HTML:

<mat-form-field class="col-sm-3">
   <mat-select placeholder="State" name="state [formControl]="stateFormControl" required>
     <mat-option *ngFor="let state of states" value="{{state.key}}">{{state.name}}
     </mat-option>
   </mat-select>
   <mat-error *ngIf="stateFormControl.hasError('required')">State is required
   </mat-error>
</mat-form-field>

typescript :

stateFormControl = new FormControl('', [
    Validators.required
]);

this.vendorForm.controls["state"].setValue(this.state);

即使我在 FormControl 声明中设置了默认值,默认情况下也没有为下拉列表设置任何内容。

最佳答案

你应该试试这个:

this.stateFormControl.setValue(this.state);

<mat-form-field class="col-sm-3">
   <mat-select placeholder="State" name="state" formControlName="state" required>
     <mat-option *ngFor="let state of states" value="{{state.key}}">{{state.name}}
     </mat-option>
   </mat-select>
   <mat-error *ngIf="stateFormControl.hasError('required')">State is required
   </mat-error>
</mat-form-field>

如果您决定更改 html,请遵循 this tutorial react 形式

所以你会用这样的东西来构建你的表单

buildForm(){
    this.vendorForm = this.fb.group({
      state: ['', Validators.required ], // <--- You don't need to instantiate FormControls
    });
}

你会在别处得到这个

<form [formGroup]="vendorForm">

关于angular - 如何在 Angular 5 中动态设置选定的下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49373984/

相关文章:

javascript - 使用单例设计模式以获得更好的代码质量

Typescript 编译正常,但发出的 JavaScript 导入失败

angular - Angular 中 unescape html 实体的正确方法是什么?

angular - 在 cPanel 上部署 Angular webApp

javascript - karma : Cannot read property * of undefined

javascript - 如何使用 typescript/javascript 正确解析 multipart/byteranges 响应?

javascript - 按名称对数组数据进行分组

javascript - 如何将 RxJS Observable 中的异步数据发送到 Angular 中的下拉列表?

Angular 5 - 未定义谷歌(谷歌地图)

angular - 错误在 Ionic 4 中找不到组件工厂...