【问题标题】:Toggling off and turning off Validators good practice in Angular?在 Angular 中切换和关闭验证器的良好做法?
【发布时间】:2019-12-20 08:28:57
【问题描述】:

我们在下面有一个 Angular 表单。出现了一个新要求,即有些人只想使用以下 10 个字段中的一些字段。所以我们的团队正在做的是:隐藏字段,并在下面的 typescript 表单和 html 中切换验证器。

问题是,这是 Angular 中的好习惯吗?我的想法是有新的表单构建器模型,可以换入和换出组件。似乎关闭验证器和 html 会留下不必要的代码,并进一步纠缠代码。如果我们创建新字段并添加切换会发生什么。现在,我们所有的 10 个字段都有切换,而且看起来越来越乱了。

只是好奇这是否是 Angular 官方文档推荐中的标准做法?

如果没关系,有没有更好的方法来管理而不是为 10 个表单控件设置 10 个布尔变量?

this.customerForm = this.formBuilder.group({
  'customerName': [null, [Validators.maxLength(50)]],
  'productBought': [null, [Validators.maxLength(50)]],
  'streetNumber': [null, [Validators.required, Validators.maxLength(64)]],
  'streetName': [null, [Validators.maxLength(8)]],
  'city': [null, [Validators.maxLength(32)]],
  'state': [null, [Validators.maxLength(16)]],
  'postalCode': [null, [Validators.maxLength(16)]],
  'postalCodeExtension': [null, [Validators.maxLength(50)]]
 }, 
}


'city': [null, this.cityShow === true ? [Validators.required, Validators.maxLength(50)] : []],


<div class="parent" *ngIf="cityShow">
    City:
     <input formControlName = "city" class = "cityclass"> 
     </input>
</div>

【问题讨论】:

  • “良好实践”问题几乎总是opinion based and not suitable for SO。一个人的“讨厌的黑客”是另一个人的“聪明的解决方案”
  • 好吧,我问的是 Angular 官方文档推荐的内容,谷歌的声明,更多关于官方供应商的标准和方法
  • 据我所知,没有官方文档。如果它有效,它就有效,如果它不正确当有人问你为什么这样做时,你能证明它是合理的吗?
  • 这可能可能更适合codereview.stackexchange.com

标签: angular typescript angular-reactive-forms angular8


【解决方案1】:

我认为创建不同的形式更合适。您可以在数组中包含必要的字段并使用 addControl

例如

controls=['customerName','streetNumber','postalCode' ]
this.customerForm = new FormGroup({})
if (controls.indexOf('customerName')>=0)
   this.customerForm.addControl('customerName',new FormControl(null,Validators.maxLength(50))
if (controls.indexOf('productBought')>=0)
   this.customerForm.addControl('productBought',new FormControl(null,Validators.maxLength(50))
if (controls.indexOf('streetName')>=0)
   this.customerForm.addControl('streetName',new FormControl(null,Validators.maxLength(8))
...

}

//In .html
<div *ngIf="controls.indexOf('customerName')>
   Customer :
   <input formControlName="customerName">
   ...
</div>

【讨论】:

  • 谢谢,您说您想要创建不同的表单构建器更合适,正如我在问题中所说的那样,或者您是否也推荐以下方法?我会研究感谢它
  • 是控制@Input 参数吗?
  • 刚刚开始阅读有趣的策略,stackoverflow.com/questions/38007236/…
  • 还有这个stackoverflow.com/questions/49266469/…,但是你真的在添加它,在答案中看到了价值
  • 似乎我们可以将答案简化为一个while循环?会研究这个,它给了我一些想法,
猜你喜欢
  • 1970-01-01
  • 2018-06-26
  • 2010-10-30
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2011-01-05
  • 2012-11-18
  • 1970-01-01
相关资源
最近更新 更多