typescript Angular 4 - 使用元素 ID 在 DOM 中显示/隐藏元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45976629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 4 - show/hide element in DOM using Id of element
提问by Elliott08
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.
我想显示一个按钮(或将其附加到其父元素),并具有特定的Id
调用时间,但我不知道如何访问组件类中的元素。
<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.
撤消按钮必须在开始时隐藏,当单击测试按钮时,它应该出现。我尝试使用*ngIf
and@ViewChild()
但它不能用于具有不同 id 的几个按钮。
回答by Vega
You can keep the selected button id in showBtn property.
您可以在 showBtn 属性中保留选定的按钮 ID。
HTML
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;
}
回答by Rohan Fating
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>
回答by devqon
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;
}