How to set formControlNames using *ngFor in Angular?

淺唱寂寞╮ 提交于 2019-12-04 19:30:50

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.

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>

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();
  }
}

Instead of setValidators(null) you can also just use clearValidators()

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

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.

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

Make sure you have [formGroup]="form" on your form tag.

Also to make it more verbose use property binding instead of interpolation over formControlName attribute

[formControlName]="i.name"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!