-1

I have a list that requires ngFor, so far so good, each item needs an input with a button that does something with the value of the input.

<mat-list role="list">
  <mat-list-item *ngFor="let item of items">{{item}}: 

    <mat-form-field>
      <input matInput>
    </mat-form-field>
    <button mat-stroked-button (click)="addCookie()">Add Cookie</button>

  </mat-list-item>
</mat-list>

Check https://stackblitz.com/edit/angular-lpiakc?file=app%2Flist-overview-example.ts

How can I pass the value of the input to the method addCookie?

export class ListOverviewExample {
  items = ['item 1', 'item 2', 'item 3'];

  addCookie() {
    console.log("here I would like to paste the value of the input field");
  }
}
rst
  • 2,510
  • 4
  • 21
  • 47
  • check [this](https://stackoverflow.com/questions/50806610/how-do-you-pass-input-value-into-a-function-on-form-submit-in-angular-6/50811039) out – ukn Mar 20 '19 at 14:38
  • 1
    @Vega i think he meant to say the value of the input – B.Benjo Mar 20 '19 at 14:38
  • Possible duplicate of [Dynamic template reference variable inside ngFor (Angular 2)](https://stackoverflow.com/questions/44440879/dynamic-template-reference-variable-inside-ngfor-angular-2) – rst Mar 20 '19 at 14:57

1 Answers1

3

You can achieve this by using #input in your html then you can pass the value of that input into the addCookie function.

<mat-list role="list">
  <mat-list-item *ngFor="let item of items">{{item}}:
    <mat-form-field>
      <input matInput #input>
    </mat-form-field>
    <button mat-stroked-button (click)="addCookie(input.value)">Add Cookie</button>
  </mat-list-item>
</mat-list>
joka00
  • 2,357
  • 1
  • 10
  • 27
  • That's it! Can you explain why that even works. I thought about that, but then I thought I'd be declaring `#input` multiple times – rst Mar 20 '19 at 14:52
  • According to this [answer](https://stackoverflow.com/a/48348156/7391435) it is uniques because you use it inside the loop. – joka00 Mar 20 '19 at 15:58