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

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

问题描述

我正在尝试使用*ngFor对数组中的对象设置表单控件.根据用户的不同,有时我会在数组中有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>

我们传递了表单控件,以便可以将其与不匹配的验证器的值进行比较,以防不匹配,在这种情况下,我们要删除验证器,因为该值不是Above WMA - Volume Price.我们设置/取消验证器,我们还需要在此处使用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.

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

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 =预览

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

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