如何在 Angular 中使用 *ngFor 设置 formControlNames? [英] How to set formControlNames using *ngFor in Angular?

查看:55
本文介绍了如何在 Angular 中使用 *ngFor 设置 formControlNames?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 *ngFor 对数组中的对象设置表单控件.根据用户的不同,有时我会在 Array 中有 1 个对象,但有时会有多个.

I'm trying to set form control using *ngFor over objects in an Array. Depending on the users sometimes I will have 1 object in the Array but other times multiple.

我的问题是我想使用循环创建一个 formControlName ,但不确定如何在组件中设置表单组验证器?像下面这样设置它们意味着如果只有 1 个对象,表单在查找其他不存在的 formControlName 时仍然无效.

My issue is that I want to create a formControlName using the loop which I can but not sure how to set form group validators in the component? Just setting them like below means if there is only 1 object the form remains invalid while looking for the other formControlName that does not exist.

因此,如果名称为Days"的第一个对象不在列表中,Days"仍将在 this.form 中并显示在控件中:

So if the first object with name:"Days" isn't in the list, "Days" would still be in this.form and shows up in controls:

数组:

indicators = [
  {name:"Days",data:[250,1]},
  {name:"Multiply Average",data:[3,.25,1]}
],

组件:

ngOnInit() {
    this.form = this._fb.group({
            "Multiply Average":['', Validators.compose([
                Validators.required
                ])],
            "Days":['', Validators.compose([
                Validators.required
                ])],
        });  
    };

模板:

  <span
     *ngFor="let i of indicators">
          {{i.name}}: 
          <md-slider
            formControlName={{i.name}}
            color="primary"
            [max]=i.data[0]
            [thumb-label]="true"
            [step]=i.data[1]
            [min]=i.data[2]>
          </md-slider>
  </span>

任何帮助都会很棒

推荐答案

您需要的是条件验证.根据选择,您需要设置所需的验证器,或者删除它们.这是一个非常简单的示例,可以为您提供想法,如果您有更多字段、更多验证等,我建议您看一下:"如何在 Angular 模型驱动表单中实现条件验证"

What you need is conditional validation. Depending on choice you need to set the wanted validators, or then remove them. This here is a very simple example to give you the idea, if you have several more fields, more validations etc I suggest you take a look at this: "How to implement conditional validation in Angular model-driven forms"

有遍历表单控件并使整个事物更具动态性的示例,但思路与下面相同.

There is sample of iterating through form controls and making the whole thing more dynamic, but the idea is the same as below.

我们可以在用户在 md-select 中做出选择时设置更改事件.您当然也可以使用 valueChanges,但我喜欢简单的更改事件:

We can set a change event on when user makes choice in the md-select. You could of course also use valueChanges, but I like a simple change event:

<md-select
  formControlName="indicator1"
  (change)="checkValue(form.get('indicator1'))">
  <md-option
      *ngFor="let indicator of indicators['indicatorlist']" 
       [value]="indicator">
       {{indicator}}
  </md-option>   
</md-select>

我们传递表单控件,以便我们可以将它与哪些验证器的值进行比较,以防它不匹配,在这种情况下,我们要删除验证器的值不是 AboveWMA - 批量价格.我们设置/取消设置验证器,我们还需要在此处使用 updateValueAndValidity():

We pass the form control so that we can compare it with the value of which validators should be removed in case it doesn't match, in this case we want to remove validator is the value is something else than Above WMA - Volume Price. We set/unset the validators and we also need to use updateValueAndValidity() here:

checkValue(ctrl) {
  if(ctrl.value != "Above WMA - Volume Price") {
    this.form.get('Multiply Average').setValidators(null);
    this.form.get('Multiply Average').updateValueAndValidity();
  } else {
    this.form.get('Multiply Average').setValidators(Validators.required);
    this.form.get('Multiply Average').updateValueAndValidity();
  }
}

你也可以使用 clearValidators()

正如已经提到的,这是一个非常粗略的样本,只是给你一个想法.

As already mentioned, this is a very crude sample to just give you the idea.

现在在 plunker 中,如果您从下拉列表中选择 Above WMA - Volume Price 以外的其他内容,则该表单现在将被视为有效(如果其他字段有效),即使有名称为 Multiply Average 的表单控件中没有值.

Now in the plunker, if you choose something else than Above WMA - Volume Price from the drop down, the form will now be considered valid (if other fields are valid), even though there is no value in that form control with name Multiply Average.

演示: https://plnkr.co/edit/h4nQfg1VYykaGgfNfnWk?p=preview

这篇关于如何在 Angular 中使用 *ngFor 设置 formControlNames?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆