如何访问打字稿文件中 ngFor 循环的当前项?
How to access the current item of an ngFor loop in the typescript file?
我有一个 firebase 变量集合,每个变量对于一个用户都是唯一的。我使用 ngFor 循环将这些变量作为卡片显示给用户。用户可以单击卡片上的按钮来访问有关该变量的更多信息(通过重定向到该变量独有的页面)。我的问题出在按钮功能上:因为按钮是通过在组件的 HTML 文件中循环显示的,所以我如何访问在 typescript 文件中单击的任何特定按钮(及其变量)零件?我是 Angular 的初学者,所以我不确定这是否是正确的方法。
ngFor 循环:
<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>
打字稿文件:
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)
}
})
})
}
}
在 ngFor 循环的每个循环中,您需要将当前项目(您将其命名为卡片)传递给点击处理程序,该处理程序接收对您需要添加到组件中的方法的引用,作为参数传递卡片:
HTML
<button mat-raised-button (click)="onClick(card)">View Space</button>
TS
onClick(card: any) {
console.log(card);
}
点击在哪里设置并不重要,只要在循环内能够传入迭代的当前项即可。您还可以处理对 <mat-card>
元素本身的点击。
我有一个 firebase 变量集合,每个变量对于一个用户都是唯一的。我使用 ngFor 循环将这些变量作为卡片显示给用户。用户可以单击卡片上的按钮来访问有关该变量的更多信息(通过重定向到该变量独有的页面)。我的问题出在按钮功能上:因为按钮是通过在组件的 HTML 文件中循环显示的,所以我如何访问在 typescript 文件中单击的任何特定按钮(及其变量)零件?我是 Angular 的初学者,所以我不确定这是否是正确的方法。
ngFor 循环:
<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>
打字稿文件:
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)
}
})
})
}
}
在 ngFor 循环的每个循环中,您需要将当前项目(您将其命名为卡片)传递给点击处理程序,该处理程序接收对您需要添加到组件中的方法的引用,作为参数传递卡片:
HTML
<button mat-raised-button (click)="onClick(card)">View Space</button>
TS
onClick(card: any) {
console.log(card);
}
点击在哪里设置并不重要,只要在循环内能够传入迭代的当前项即可。您还可以处理对 <mat-card>
元素本身的点击。