0

Hey guys i assigned the id to each bootstrap card and when i render it in html component it gets correctly rendered but how do i retreive it in the console? means on clicking the "Add to Cart" button i want to pass it to the .component.ts file ..How do i do that?

html component

<div class=" row justify-content-md-center">
<div class="col-md-3 describe" *ngFor="let p of filteredproducts 
;let i=index">  ///here i assigned the id
 <mdb-card class="mdb">
<mdb-card-img src="{{p.imageurl}}" alt="Card image cap"></mdb-card- 
img>
<mdb-card-body>
  <mdb-card-title>
    <h4>{{p.title}}</h4>
  </mdb-card-title>
  <mdb-card-text> {{p.price}}
  </mdb-card-text>
<div>
<div *ngIf="counter==0">
   <button class="button" id="btn" (click)="onclick()" åmdbBtn 
 type="button" color="primary" block="true" mdbWavesEffect>Add to 
 Cart</button>
 </div>
 <div *ngIf="counter>0">

 </div>
 </div>
 </mdb-card-body>
 </ mdb-card> </div>
 </div>

.component.ts file

export class HomeComponent implements OnInit {
counter=0

constructor(private route:ActivatedRoute,private 
router:Router,private prservice:Productservice) {


ngOnInit() {

}

onclick(){
this.counter++
console.log(this.counter)
}


}

here i need to retreive the id

Ratnabh Kumar Rai
  • 554
  • 2
  • 7
  • 24
  • Have you looked at this https://stackoverflow.com/questions/36006894/angular2-get-clicked-element-id/36007029 ? – Nik Feb 15 '19 at 07:02
  • Possible duplicate of [Angular2 get clicked element id](https://stackoverflow.com/questions/36006894/angular2-get-clicked-element-id) – k.s. Feb 15 '19 at 07:02

2 Answers2

1

pass it as a parameter to click function.

 (click)="onclick(i)" 

onclick(i: string){
  this.counter++
  console.log(i)
}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1

You can pass the product and its property itself because it might help in future to get many attributes of product instead of just id. But here I have passed both as you need them.

 <button class="button" id="btn" (click)="onclick(product,i)" 
     type="button" color="primary" block="true" mdbWavesEffect>Add to 
     Cart</button>

ts file

onclick(product,index){
this.counter++
console.log(this.counter)
}
Hameed Syed
  • 3,939
  • 2
  • 21
  • 31