Angular 4 - 使用Renderer 2和Element.querySelector()修改html元素的样式

时间:2018-01-04 14:23:08

标签: angular dom renderer

在Angular 4组件中有这样的点击事件处理程序是否可以?

 showPhotoDeleteButton( event ) 
    { 
        var photoDeleteButton = (<Element>event.target).querySelector('.photo-delete'); 
        this.renderer.setStyle(photoDeleteButton, "display", "block"); 
    }

    hidePhotoDeleteButton( event ) 
    { 
        var photoDeleteButton = (<Element>event.target).querySelector('.photo-delete'); 
        this.renderer.setStyle(photoDeleteButton, "display", "none"); 
    }

正如我所读到的那样,不建议使用直接DOM操作,因为Angular是一个平台,并不总是在浏览器上运行,也在Web工作者等上运行。

1 个答案:

答案 0 :(得分:0)

在我看来,最好的方法是使用ngIf并在事件中切换isDeleteButtonVisible:

*ngIf="isDeleteButtonVisible"

https://angular.io/api/common/NgIf

您也可以使用NgClass或NgStyle

https://angular.io/api/common/NgClass
https://angular.io/api/common/NgStyle
https://coryrylan.com/blog/introduction-to-angular-ngclass-and-ngstyle

例如,你可以使用NgClass然后在你的show和hide事件中只将一个属性从true更改为false并且按钮是否可见

相关问题