angular change an input element’s valid condition. I almost always use ReactiveForms because the API offers lots of useful tools to build simple to complex forms. In your case, a solution could be something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import { Component } from '@angular/core'; import { FormControl, FormGroup, FormArray, Validators } from '@angular/forms'; @Component({ selector: 'my-app', template: ` <form [formGroup]="form"> <input formControlName="newItem"> <button type="button" (click)="addItem()" [disabled]="!item.valid">ADD</button> <hr> <button type="button" (click)="submit()" [disabled]="!items.valid">SUBMIT</button> <hr> <ul> <li *ngFor="let item of items.controls; let i = index">{{ item.value }} - <button type="button" (click)="removeItem(i)">DELETE</button></li> </ul> </form> ` }) export class AppComponent { form: FormGroup; get item() { return this.form.get('newItem') as FormControl; } get items() { return this.form.get('items') as FormArray; } constructor() { this.form = new FormGroup({ newItem: new FormControl('', Validators.required), items: new FormArray([], Validators.required), }) } addItem() { this.items.push(new FormControl(this.item.value)); this.item.reset(''); } removeItem(i: number) { this.items.removeAt(i); } submit() { console.log(this.form.value); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.