$ cd ng new ngmatdynamicinput
$cd ngmatdynamicinput
$ ng add @angular/material
Import ‘MatCardModule,MatInputModule,FormsMuodule’ to app modules
Open app.component.ts and create an array
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.scss’]
})
export class AppComponent {
questions = [{ value: ‘’ }];
title = ‘ngmatdynamicinput’;
}
Now we’ll create material input box and add button
<form #formRef=”ngForm”>
<div *ngFor=”let word2 of questions; let in=index” class=”col-md-8">
<mat-card-content>
<mat-form-field class=”example-full-width”>
<mat-label>Add a question</mat-label>
<input type=”text” matInput [(ngModel)]=”questions[in].value” name=”name{{in}}” class=”form-control”
#name=”ngModel” required />
<mat-error [hidden]=”questions[in].value”>Field is required </mat-error>
</mat-form-field>
</mat-card-content>
<br />
</div>
<button [disabled]=”!formRef.form.valid” (click)=”add()”>Add input</button>
</form>
Now update the app component with add function
add() {
this.questions.push({ value: ‘’ });
}
and finally it is ready! now run “ng serve”
Output
Sample project on git here