[Fixed] use ngModel inside <p> tag in Angular 8

Issue

Html code:

<div class="col-md-4" *ngFor="let card of allCards">
<p class="card-text">Card Color: {{card.color}}</p>
<button type="button" class="btn btn-sm btn-primary product-btn" (click)="addCard()">Add Card</button>"

Here I also want to bind the value "card.color" into another variable (maybe using ngModel) so that I can use it inside my typescript file in angular 8.

I tried the below but not working:

<p class="card-text" [(ngModel)]="cardColor">Card Color: {{card.color}}</p>

Solution

You could send the contents to the button click event’s handler.

Template (*.html)

<div class="col-md-4" *ngFor="let card of allCards">
<p class="card-text">Card Color: {{card.color}}</p>
<button 
  type="button" 
  class="btn btn-sm btn-primary product-btn" 
  (click)="addCard(card.color)"
>
  Add Card
</button>

Controller (*.ts)

addCard(color: any) {
  // use `color` here
}

Leave a Reply

(*) Required, Your email will not be published