Reputation: 145
I want to show a button (or append it to its parent element) with a specific Id
when a function is called but I don't know how to access the element in the component class.
<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>
Component class:
private showBtn = false;
showUndoBtn(btnId: number) {
// show btn with id btnId in DOM
}
The undo button must be hidden at the beginning and when Test button is clicked, it should appear. I tried using *ngIf
and @ViewChild()
but it can not be used for several buttons with different id.
Upvotes: 5
Views: 19329
Reputation: 2133
Easiest way where you don't need to call separate function to implement
<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>
Upvotes: 4
Reputation: 28708
You can keep the selected button id in showBtn property.
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>
Typescript
showBtn=-1;
showUndoBtn(index){
this.showBtn=index;
}
Upvotes: 8
Reputation: 13997
The easiest way is to use properties on your repeated items, something like this:
<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>
And your component:
showUndoBtn(item) {
// show btn with id btnId in DOM
item.showButton = true;
}
Upvotes: 3