![](/img/trans.png)
[英]Calling a method on a particular instance of a React component from another component
[英]Hide a particular instance of a repeating component
我有一個帶有 ngFor 迭代集合的表。 對於集合中的每個項目,它將生成包含單個單元格的行。 該單元格包含一個按鈕和自定義組件。 自定義組件有一個 ngIf 指令,該指令僅在設備被視為在線時顯示自定義組件。 我還希望能夠通過單擊按鈕來切換自定義組件的可見性。 如何將表格單元格中自定義組件的特定實例傳遞給 onExampleBtnClick() function? 我不希望顯示/隱藏自定義組件的所有實例,只顯示與單擊的按鈕共享單元格的實例。 謝謝
<table>
<tr *ngFor="let item of items;let indexOfelement=index;">
<td>
<button type="button" (click)="onExampleBtnClick($event)" #ExampleButton>Click Me</button>
<custom-comp *ngIf="showIfDeviceOnline"></custom-comp>
</td>
</tr>
</table>
您可以在數據數組上創建另一個屬性,該屬性將跟蹤組件是否需要顯示。 您無需使用 map function 創建一個新的 object 數組,如下所示。
export class AppComponent {
title = "CodeSandbox";
Items:string[] = ['Apple','Oranges'] ;
data: any = null;
ngOnInit(){
this.data = this.Items.map(x=> {
return {
name: x,
show:true
}
});
}
hide(item){
item.show = false;
}
}
並基於此,您可以在容器上應用 * ngIf條件,如下所示。
<div>
<div *ngFor="let item of data">
<ng-container *ngIf="item.show">
<button type="button" (click)="hide(item)"> Click Me</button>
<app-custom></app-custom>
</ng-container>
</div>
</div>
這是代碼框https://codesandbox.io/s/pedantic-forest-871qc?file=/src/app/app.component.ts:160-449
另一種方法是創建一個映射器 object,它將跟蹤數組中每個項目的狀態並根據狀態隱藏組件。
本地參考是我一直在尋找的。 我可以將自定義組件包裝在一個 div 中並應用 #CustComp 的本地引用,然后將 CustComp 傳遞給 onExampleBtnClick function。 它將引用實際實例並允許我定位它的隱藏屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.