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.
Completely hiding elements can be done in 3 ways: via the CSS property display , e.g. display: none; via the CSS property visibility , e.g. visibility: hidden; via the HTML5 attribute hidden , e.g. <span hidden>
Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.
To hide/show an element in TypeScript, use the style. display property to determine if the element is shown or hidden. If its display property is set to none , show the element by setting it to block , otherwise hide the element by setting its display property to none .
How do you hide a button after it is clicked in angular? First set up a Boolean variable for the show hide like public show:boolean = false. Next, set up a function that is tied to the click event of a button or some event on the dom.
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;
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With