2017-08-31 67 views
1

我想在調用某個函數時顯示一個按鈕(或將其追加到其父元素),但我不知道如何訪問元件類中的元素。Angular 4 - 使用元素的ID在DOM中顯示/隱藏元素

private showBtn = false; 

showUndoBtn(btnId: number) { 
    // show btn with id btnId in DOM 
} 

撤銷按鈕必須在一開始被隱藏,點擊測試按鈕時,應顯示:

<div *ngFor="let item of items; let i = index;"> 

    <button [attr.id]="'undoBtn'+i" *ngIf="showBtn" class="editBtn" md-raised-button color="primary"> 
     <md-icon>undo</md-icon>Undo 
    </button> 

    <button (click)=showUndoBtn(i) md-raised-button color="primary">Test</button> 
</div> 

組件類。我嘗試使用*ngIf@ViewChild(),但它不能用於多個不同ID的按鈕。

回答

1

你也可以在showBtn屬性選擇按鈕的ID。

HTML

<div *ngFor="let item of items; let i = index;"> 

     <button [attr.id]="'undoBtn'+i" *ngIf="showBtn===i" class="editBtn" md-raised-button color="primary"> 
      <md-icon>undo</md-icon>Undo 
     </button> 

     <button (click)=showUndoBtn(i) md-raised-button color="primary">Test</button> 
</div> 

打字稿

showBtn=-1; 

showUndoBtn(index){ 
    this.showBtn=index; 
} 
+1

該解決方案是如此簡單容易的方法,非常感謝 ! – Elliott08

1

最簡單的方法是在你的物品重複使用性能,是這樣的:

<div *ngFor="let item of items; let i = index;"> 

    <button [attr.id]="'undoBtn'+i" *ngIf="item.showButton" class="editBtn" md-raised-button color="primary"> 
     <md-icon>undo</md-icon>Undo 
    </button> 

    <button (click)=showUndoBtn(item) md-raised-button color="primary">Test</button> 
</div> 

而且您的組件:

showUndoBtn(item) { 
    // show btn with id btnId in DOM 
    item.showButton = true; 
} 
1

,你不需要調用單獨的函數來實現

<div *ngFor="let item of items; let i = index;"> 

     <button [attr.id]="'undoBtn'+i" *ngIf="showBtn===i" class="editBtn" md-raised-button color="primary"> 
      <md-icon>undo</md-icon>Undo 
     </button> 

     <button (click)='showBtn=i' md-raised-button color="primary">Test</button> 
</div>