0

I am trying to create a table like input form in Angular.

My current solution is like this:

html:

<form (ngSubmit)="doSomething()">
<table>
    <thead>
        <tr>First Name</tr>
        <tr>Last Name</tr>
        <tr>Phone Number</tr>
    </thead>
    <tbody>
        <tr *ngFor="let person of team"></tr>
        <td><input type="text" [(ngModel)]="person.first_name" [ngModelOptions]="{standalone: true}" required></td>
        <td><input type="text" [(ngModel)]="person.last_name" [ngModelOptions]="{standalone: true}" required></td>
        <td><input type="text" [(ngModel)]="person.phone" [ngModelOptions]="{standalone: true}" required></td>
    </tbody>
</table>
<button (click)="addNewEntry()"></button>
<button type="submit">Submit</button>

ts:

team : new Array()
addNewEntry(){
    this.team.push({
        'first_name':'',
        'last_name':'',
        'phone':null})
}

doSomething(){
};

However, if I do it this way, the 'required' validator does not work on clicking the Submit button.

I tried couple of ways:

  1. instead of setting [ngModelOptions]="{standalone: true}" , I tried name='person:{{$index}}'. Does not work.

  2. Tried to set up a ngForm and instead of using ngModel, use formControlName. I can't figure out how to dynamically create formControlName and validate them.

May I ask if there is a way to get this done properly?

Thanks!

Qiao Jian
  • 11
  • 4

1 Answers1

0

Your best bet is to use Angular ReactiveFormsModule. ReactiveFormsModule support FormArray and will make it easy to perform validation and get the form item values.

For reference, check out:

  1. https://angular.io/guide/reactive-forms
  2. https://stackoverflow.com/a/48527939/9194488
ilogs
  • 111
  • 3