我有一个id为1的div。我试图动态地将显示设置为none。有没有一种Angular的方法来做这件事。目前,我正在使用香草javascript。我问动态地做这个,因为将有超过60div将从一个数组创建。
在我的html
<div *ngFor="let item of items; i = index;">
<div id={{i}} (click)=hideDiv()></div>
</div>
In my method
hideDiv() {
return document.getElementById('1').style.display = "none";
}
这是有效的,但我正在寻找做上面的Angular的方式。
这是建议我使用@ViewChild。这是我所改变的。我不能使用模板引用变量作为htmldiv是动态创建的。除非有人能让我知道如何动态地创建模板变量。虽然我不认为可以用循环来创建模板变量
@ViewChild('imgId', { static: true }) elementRef: ElementRef<HTMLDivElement>;
imgId: string;
然后在方法中我有:
this.imgId = event.path[0].attributes[1].value;
this.elementRef.nativeElement.style.display = "none";
event.path [0] .attributes[1]。Value获取图像的id。当我对它进行控制台日志时,imgId会显示。它仍然没有将div上的显示改为none。我也得到了错误:无法读取未定义的属性(正在读取'nativeElement')
是的,你可以使用Angular中的ViewChild查询来做到这一点。在组件中,像这样定义一个查询:
@ViewChild('#1') elementRef: ElementRef<HTMLDivElement>;
在组件中实现afterviewit接口,并在其中使用:
this.elementRef.nativeElement.style.display = "none";
您可以简单地使用ngIf
<组件/strong>
shouldDisplay: boolean = true;
hide(): void {
this.shouldDisplay = false;
}
show(): void {
this.shouldDisplay = true;
}