为了账号安全,请及时绑定邮箱和手机立即绑定

有没有一种方法可以将一些用于角度反应形式控件的 get 方法包装到一个函数中

有没有一种方法可以将一些用于角度反应形式控件的 get 方法包装到一个函数中

湖上湖 2022-01-01 18:35:49
美好的一天,这是我第一次在这里提出问题并且我对解决方案非常积极,在我的组件中,我在下面设置了一个角度反应形式和一些 getter(我称之为 lols)但它有点混乱,我的意思是这个表单控件实际上很多,请问有什么方法可以将这些 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">
查看完整描述

2 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

是的,您可以编写一个返回 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>


查看完整回答
反对 回复 2022-01-01
?
繁华开满天机

TA贡献1816条经验 获得超4个赞

像这样尝试:


ngOnInit() {


    this.formName.valueChanges.subscribe(value => {

      Object.keys(this.formName.controls).forEach((key: string) => {

        console.log(this.formName.get(key).value);

      });

    });

}


查看完整回答
反对 回复 2022-01-01
  • 2 回答
  • 0 关注
  • 132 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信