angular - Form Validation for Dynamically added and removed form Elements -
i have form element in can add , remove value dynamically.
for example in below code domain can added , removed using adddomain , removedomain
<div *ngfor="let item of company.domains"> <div class="row"> <div class="col-lg-9"> <input type="text" class="form-control" ngcontrol="domainc" [(ngmodel)]="company.domains[i]"> </div> <div class="col-lg-3 pull-left"> <a (click)="removedomain(i)"> <i class="fa fa-times"></i></a> <a (click)="adddomain()"> <i class="fa fa-plus"></i></a> </div> </div> </div>
i need validate these on submit since added values required. working control in angular 2, unable figure out how apply validation such elements, appreciated.
you can bind form form model
<form [ngformmodel]="form"> <div *ngfor="let item of controls let idx=index"> <div class="row"> <div class="col-lg-9"> <label>{{item.name}}</label><input type="text" class="form-control" [ngcontrol]="item.name" [(ngmodel)]="values[item.name]"> {{item.control.errors | json}} </div> <div class="col-lg-3 pull-left"> <div><button (click)="removedomain(i)">remove</button></div> </div> </div> </div> <hr> <div> <label>control name</label><input #nameinput> <label>validator</label><select #validatorinput> <option>required</option> <option>minlength</option> <option>maxlength</option> </select> <label>length</label><input type="number" #lengthinput> <button (click)="adddomain(nameinput.value, validatorinput.value, lengthinput.value)">add</button> </div>
export class app { form:controlgroup; controls [ { name: 'name', control: new control('', validators.required) }, { name: 'password', control: new control('', validators.minlength(3))} ]; values = { name: '', password: '', } constructor(fb:formbuilder) { this.form = fb.group(); this.name = 'angular2 (release candidate!)' this.controls.map((item) => { console.log('map item', item); this.form.addcontrol(item.name, item.control); }); } removedomain(i) { this.values[this.controls[i].name]=undefined; this.form.removecontrol(this.controls[i].name); this.controls.splice(i); this.form.controls.foreach(c => c.updatevalueandvalidity()); } adddomain(name, validator, length) { this.values[name] = ''; var validator; if(length) { validator = validators[validator](length); } else { validator = validators[validator]; } let newctl = new control('', validator); this.controls.push({name: name, control: newctl}); this.form.addcontrol(name, newctl); //this.controls.foreach(c => this.form.controls[c.name].updatevalueandvalidity()); } }
Comments
Post a Comment