我正在尝试在 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/