有没有一种方法可以把角反应形式控制的一些get方法包装成一个函数



您好,这是我第一次在这里提问,我对解决方案非常肯定。在我的组件中,我在下面有一个角度反应表单设置和一些getter(我称之为lol(,但它有点乱,我的意思是这个表单控件实际上很多,请有没有一种方法可以将这些getter封装到一个函数中,这样我就不会有几行代码了。我是javascript新手。

formName = new FormGroup({
accNum: new FormControl('', [Validators.required]),
appName: new FormControl('', Validators.required),
...
Addr: new FormControl('', Validators.required),
});
//form getters
get accNum(){
return this.formName.get('accNum')
}
get appName(){
return this.formName.get('appName');
}
...
get Addr(){
return this.formName.get('Addr');
}

我这样做是为了能够像这样在我的html模板中设置表单控件。

<input formControlName="accNum" type="text" class="form-control">
<input formControlName="appName" type="text" class="form-control">
<input formControlName="Addr" type="text" class="form-control">

谢谢你的回复。

这样尝试:

ngOnInit() {
this.formName.valueChanges.subscribe(value => {
Object.keys(this.formName.controls).forEach((key: string) => {
console.log(this.formName.get(key).value);
});
});
}

演示

是的,您可以编写一个返回formControl对象的泛型方法。

.ts文件中,编写这样的函数。

getFormControl(controlName: string) {
//return the formControl object of the respective 'controlName'
return this.formName.get(controlName);
}

然后,在您的模板中

<input formControlName="accNum" type="text">
<span *ngIf="getFormControl('accNum').errors?.required">
accNum can't be empty
</span>
<input formControlName="accName" type="text">
<span *ngIf="getFormControl('accName').errors?.required">
accName can't be empty
</span>

最新更新