我正在尝试在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>
打字稿:
stateFormControl = new FormControl('', [
Validators.required
]);
this.vendorForm.controls["state"].setValue(this.state);
即使我在FormControl声明中设置了默认值,默认情况下也没有为下拉列表设置任何内容。
答案 0 :(得分:0)
绑定到<option>
代码中的value属性:
<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>
答案 1 :(得分:0)
你应该试试这个:
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的反应式
进行操作所以你将用这样的东西构建你的表单
buildForm(){
this.vendorForm = this.fb.group({
state: ['', Validators.required ], // <--- You don't need to instantiate FormControls
});
}
你将在其他地方拥有这个
<form [formGroup]="vendorForm">