Angular 4 - Can I create a form dynamically using ngFor?
I am trying to dynamically create an editable form using ngFor. Basically data grid and what I will be using on some other systems - maybe the way I should go, but I tried it first.
<form #employeeForm="ngForm">
<tr *ngFor="let employee of newEmployees | filter:filterCriteria; let i = index" [class.active]="i == selectedRow" [attr.rowIndex]="i">
<td class="clickable" (click)="showEmployee(i)">
<div>{{employee.avatar}}</div>
</td>
<td>
<md-input-container dividerColor="accent" >
<input mdInput placeholder="name" value={{employee.name}} name="employee-name-{{employee.id}}" [(ngModel)]="employee-name-{{employee.id}}"/>
</md-input-container>
</td>
...
<td>
<md-icon (click)="saveEmployeeChanges(employee.id)">save</md-icon></td>
</tr>
</form>
Am I barking the wrong tree here? If this can work, how do I access each input field (there will be more) from within the component? And how do I get the values โโof each field in the row (not just the one that changed last).
source to share
There are many ways to solve this problem.
You saw this as an example: https://angular.io/guide/dynamic-form
But you have an option. You can change this:
<md-icon (click)="saveEmployeeChanges(employee.id)">
:
<md-icon (click)="saveEmployeeChanges(employeeForm)">
This will pass the form and all associated controls to your component class.
To access the controls on a form you can use:
employeeForm.get('name').value;
You can read more about Angular docs here: https://angular.io/guide/reactive-forms#inspect-formcontrol-properties
source to share