简体   繁体   中英

Validation in Angular2 FormGroup for dynamically added inputs

I have a form in which inputs are added on the click of a button.

addInput() {
    let input: {} = {
      "text": null
    };
    this.arr.push(domain); 
      let key = 'textC_' + (this.arr.length - 1);
      this.form.controls[key] = new FormControl("", Validators.required)
  }

I am using following code to render on HTML:

<div class="form-group row">
   <label>Input</label>
   <div class="col-sm-9">
      <ANY *ngFor="let item of arr; let i = index">
         <div class="row">
            <div class="col-sm-6 top5">
               <input type="text" formControlName="textC_{{i}}"  id="name" [(ngModel)]="arr[i].text" >
               <div class="help-block" *ngIf="!form.controls.textC_{{i}}.valid  > 
               Value is required
            </div>
         </div>
   </div>
   </ANY>
</div>
</div>

How to render validation messages using this approach.

form.controls.textC_{{i}}.valid is not working

Any alternate?

Using angular rc5

Dont use expression syntax {{}}. The ngIf directive already treats the assignment as an expression. try:

<div class="help-block" *ngIf="!form.controls['textC_' + i].valid"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM