sch*_*uno 2 html typescript angular-material angular
在我的 Angular v6 应用程序中,我尝试显示一个下拉列表并将其设置为required基于布尔值,它设置在复选框的值上。这是我的模板中的代码片段(includeModelVersion最初设置为false):
<mat-checkbox class='matCheckbox' (change)="includeModelVersion = !includeModelVersion">Run Model</mat-checkbox>
<mat-form-field *ngIf="includeModelVersion">
<mat-select placeholder="Select Model Version" formControlName="modelVersionCtrl" [required]="includeModelVersion">
<mat-option *ngFor="let model of modelData" [value]="model?.MODEL_VERSION">{{model.MODEL_VERSION}}</mat-option>
</mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
在我的 .ts 构造函数中,我定义了布尔值:
includeModelVersion: boolean = false;
Run Code Online (Sandbox Code Playgroud)
使用 *ngIf 可以正确显示下拉列表,但问题与[required]="includeModelVersion"内有关mat-select。
如果我不选中该复选框,则表单可以正常提交,但如果我选中该复选框然后取消选中它,则下拉列表仍然是必需的,即使includeModelVersion=false.
我在这里遗漏了一些东西,还是我错误地定义了一些东西?
如果您使用反应式表单,则可以动态地将“必需”验证器添加到 formControl 中。
this.form.controls["modelVersionCtrl"].setValidators(Validators.required);
Run Code Online (Sandbox Code Playgroud)
您可以根据组件类中的某些条件执行此语句。