Very Simple usage of ngModel

2019-08-29 13:33发布

问题:

I have this very simple table body that generates a table based on the activityDays and for each clientType creates columns with some inputs.

It works well.

<tr *ngFor="let c of counter(environment.activityDays); let day = index" class="text-center hover-table" [(ngModel)]="clients">
  <td>{{day+1}}</td>
  <td *ngFor="let clientType of clientTypes">
    <div>
      <input class='text-center field' value='0' type='number' min='0' required />
    </div>
  </td>
</tr>

My problem now is how do I retrieve the data from this inputs? I want for example

ClientType1 , Day 1 , 20 clients

ClientType2 , Day 1 , 10 clients

etc...

I made a class but I don't know how to apply this.

export class Client {
  day:number;
  type:string;
  amount:number;
}

And then when I submit my form i just want to show the objects on the log for now.

 clients:Client[];

 create() {
  console.log(this.clients);
 }

回答1:

You could do something like this:

Component.ts:

export class Component  {
  clientTypes = ['','','',''];
  clientTypesInputs = [];
}

Component.html:

<table>
    <tr>
        <td *ngFor="let clientType of clientTypes; let in=index">
      <div>
        <input value="0" type="number" min="0" required [(ngModel)]="clientTypesInputs[in]"  />
      </div>
    </td>
    </tr>
</table>

<ul>
  <li *ngFor="let clientTypeInput of clientTypesInputs">{{clientTypeInput}}</li>
</ul>

clientTypesInputs is going to have the inputs at the index that they need to be acording to clientTypes array position.

Here is a working example:

https://stackblitz.com/edit/angular-artq8x