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

问题描述 投票:0回答:1

在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 worker等上运行。

angular dom renderer
1个回答
0
投票

在我看来,最好的方法是使用ngIf和切换是在事件中删除按钮可见:

*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并且按钮是否可见

© www.soinside.com 2019 - 2024. All rights reserved.