【问题标题】:How to access the current item of an ngFor loop in the typescript file?如何访问打字稿文件中 ngFor 循环的当前项?
【发布时间】:2022-01-17 12:55:52
【问题描述】:

我有一个 firebase 变量集合,每个变量都是用户独有的。我使用 ngFor 循环将这些变量作为卡片显示给用户。用户可以单击卡片上的按钮来访问有关该变量的更多信息(通过被重定向到该变量唯一的页面)。我的问题在于按钮功能:因为按钮是通过在组件的 HTML 文件中循环显示的,我如何访问组件的打字稿文件中单击的任何特定按钮(及其变量)?我是 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)
        }
      })  
    })
    
  }
}

【问题讨论】:

标签: angular typescript google-cloud-firestore firebase-authentication


【解决方案1】:

在 ngFor 循环的每个循环中,您需要将当前项目(您将其命名为 card)传递给 click 处理程序,该处理程序接收对您需要添加到组件中的方法的引用,并将 card 作为参数传递:

HTML

<button mat-raised-button (click)="onClick(card)">View Space</button>

TS

onClick(card: any) {
   console.log(card);
}

只要在循环内部能够传入迭代的当前项,在哪里设置点击并不重要。您还可以处理对&lt;mat-card&gt; 元素本身的点击。

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2018-07-29
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多