bno*_*man 5 typescript angular
我正在尝试设置 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>
Run Code Online (Sandbox Code Playgroud)
打字稿:
stateFormControl = new FormControl('', [
Validators.required
]);
this.vendorForm.controls["state"].setValue(this.state);
Run Code Online (Sandbox Code Playgroud)
即使我在 FormControl 声明中设置默认值,默认情况下也不会为下拉列表设置任何内容。
你应该尝试这个:
this.stateFormControl.setValue(this.state);
Run Code Online (Sandbox Code Playgroud)
或者
<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>
Run Code Online (Sandbox Code Playgroud)
如果您决定更改 html,请按照本反应式表单教程进行操作
所以你将用这样的东西构建你的表单
buildForm(){
this.vendorForm = this.fb.group({
state: ['', Validators.required ], // <--- You don't need to instantiate FormControls
});
}
Run Code Online (Sandbox Code Playgroud)
你会在其他地方得到这个
<form [formGroup]="vendorForm">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14422 次 |
| 最近记录: |