我创建了一个用于从用户获取数据的简单表单,我想仅在输入字段之一中包含数据的情况下才激活提交按钮。这是我的代码:
HTML:
`合同号
<mat-form-field>
<mat-label>Instance No.</mat-label>
<input matInput id="instanceno" placeholder="" name="instanceno" formControlName="instanceno">
</mat-form-field>
<div *ngIf="form.get('instanceno').hasError('pattern')" class="error">Only Numeric Value Allowed
</div>
<br>
<mat-form-field>
<mat-label>Serial No.</mat-label>
<input matInput id="serialno" placeholder=""name="serialno" formControlName="serialno">
</mat-form-field>
<br>
<mat-form-field>
<mat-label>Customer No.</mat-label>
<input matInput id="customerno" name="customerno" placeholder="" formControlName="customerno">
</mat-form-field>
<br>
<button mat-button type="submit" [disabled]="!form.valid" matDialogClose >Submit</button>
<button mat-button mat-dialog-close>Cancel</button>
`
TS:
this.form = new FormGroup({
contractno: new FormControl(''),
serialno: new FormControl(''),
instanceno: new FormControl('', Validators.pattern('[0-9]*')),
customerno: new FormControl('')
});
我的解决方法是将表单控件存储在一个结构中,该结构使每次表单更改时检查其值变得简单。
与其内联构建表单,不如将表单控件本身存储在单独的变量中。
form: FormGroup;
private formControls: {
contractno: FormControl;
serialno: FormControl;
instanceno: FormControl;
customerno: FormControl;
};
private formControlsArray: FormControl[];
ngOnInit() {
this.formControls = {
contractno: new FormControl(''),
serialno: new FormControl(''),
instanceno: new FormControl('', Validators.pattern('[0-9]*')),
customerno: new FormControl('')
};
this.formControlsArray = Object.keys(this.formControls)
.map(key => this.formControls[key]);
this.form = new FormGroup(this.formControls);
}
然后订阅表单值更改,每次表单更改时都要检查表单控件数组中是否存在有效值。
hasValue = false;
private destroyed$ = new Subject();
ngOnInit() {
// build the form here
this.form.valueChanges.pipe(
takeUntil(this.destroyed$)
).subscribe(() => {
this.hasValue = this.formControlsArray.some(x => x.value.length > 0);
});
}
ngOnDestroy() {
this.destroyed$.next();
}
然后,您可以将按钮的disabled
状态绑定到hasValue
属性。
<form [formGroup]="form">
<!-- the form -->
<button [disabled]="!hasValue">
Submit
</button>
</form>
因此,如果您想加强值检查,例如仅将非空白值视为有效,则只需更新此功能即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句