我在表单上有一个与模式变量绑定的切换按钮,mat-form-fields是可见的switchCaes条件基础,它是由toggleButton值驱动的(请参见代码段)。在matInput-to中,所需的验证也从切换按钮的值派生而来,我将模式选择为单个,matInput-form仅按预期可见,但是我的窗体仍然无效,我不知道为什么,这应该将matInput-设置为false至。
mytest.html
<shell-panel>
<mat-card-content>
<ng-container [ngSwitch]="this._form.value.mode">
<div class="mat-card-row">
<mat-form-field>
<input matInput required placeholder={{placeHolder}} maxlength="12" pattern="someRegEx" formControlName="from " />
</mat-form-field>
<mat-divider></mat-divider>
</div>
<div class="mat-card-row" *ngSwitchCase="'range'">
<mat-form-field>
<input matInput [required]="this._form.value.mode=='range'" placeholder="to" pattern="someRegEx" formControlName="to" />
</mat-form-field>
</div>
</ng-container>
</mat-card-content>
<mat-button-toggle-group name="fontStyle" formControlName="mode" (click)="resetForm(this._form.value.mode)" >
<mat-button-toggle value="single">Single</mat-button-toggle>
<mat-button-toggle value="range">Range</mat-button-toggle>
</mat-button-toggle-group>
<div class="actions">
<button mat-fab (click)="onSubmit();" class=".add-button" [disabled]="_form.invalid" matTooltip="Search">
<mat-icon>search</mat-icon>
</button>
</div>
mytest.ts
resetForm(mode: string) {
this._form.controls['mode'].setValue(mode);
this._form.controls['from'].setValue('');
this._form.controls['to'].setValue('');
}
如我所见,你有相对形式。使用以下方法,您可以做两件事来查找哪些字段无效。只需将formGroup传递给下面的方法,然后控制台记录返回的输出即可。
public findInvalidControls() {
const invalid: string[] = [];
const controls = this._form.controls;
for (const name in controls) {
if (controls[name].invalid) {
invalid.push(name);
}
}
return invalid;
}
并且添加上述方法后,将其传递到console.log console.log(this.findInvalidControls())
。您将能够相应地看到无效的控件。
第二,如果控制台中没有错误,并且仍然无法找到任何错误,则可以在切换事件中从控制器更新表单的值和有效性。通过此代码段并尝试this._form.updateValueAndValidity();