How to access the current item of an ngFor loop in the typescript file?
I have a firebase collection of variables, each unique to a user. I use an ngFor loop to display these variables to the user as cards. The user is able to click a button on a card to access more information about that variable (by being redirected to a page unique to that variable). My issue comes in the button functionality: because the buttons are displayed by being looped through in the HTML file of the component, how do I access whichever specific button that was clicked (and its variable) in the typescript file of the component? I'm a beginner to Angular so I'm unsure if this is even the right approach.
The ngFor loop:
<div fxLayout="row wrap">
<div class = 'content' *ngFor="let card of cards">
<mat-card>
<mat-card-content>
<mat-card-title>
<h4>{{card.spaceName}}</h4>
</mat-card-title>
<mat-card-actions>
<button mat-raised-button>View Space</button>
</mat-card-actions>
</mat-card-content>
</mat-card>
</div>
</div>
The typescript file:
interface Space {
}
@Component({
selector: 'app-viewspaces',
templateUrl:'./viewspaces.component.html',
styleUrls: ['./viewspaces.component.css']
})
export class NewViewspacesComponent implements OnInit {
cards : Space[];
users : Observable<any[]>;
spaces : Observable<any[]>;
machines : Observable<any[]>;
constructor(private firestore: AngularFirestore) {
this.spaces = firestore.collection('spaces').valueChanges();
}
ngOnInit(): void {
const auth = getAuth();
const email = auth.currentUser?.email
this.cards = []
this.spaces.subscribe(res =>{
res.forEach(item =>{
if(item.email == email){
console.log(item.spaceID)
this.cards.push(item)
}
})
})
}
}
Solution 1:
In each cycle of the ngFor loop, you need to pass the current item (you named it card) - into the click handler, which receives a reference to a method you need to add into your component, passing as argument the card:
HTML
<button mat-raised-button (click)="onClick(card)">View Space</button>
TS
onClick(card: any) {
console.log(card);
}
It does not really matter where you set the click as long as inside the loop to be able to pass in the current item of the iteration. You could also handle the click on the <mat-card>
element itself.