代码之家  ›  专栏  ›  技术社区  ›  Karan

角度5-动态向特定元素添加样式

  •  6
  • Karan  · 技术社区  · 8 年前

    我在我的项目中使用的是Angular5.2,并且是Angular框架的新手。我的组件HTML如下所示:

    enter image description here

    我想动态地将style=“top:200px;”添加到上面的屏幕截图中带有class=“app alerts”的突出显示元素中。类为“app alerts”的div元素被添加到呈现的dom中。

    请建议更改代码。

    2 回复  |  直到 8 年前
        1
  •  13
  •   Aravind    8 年前

    根据我们的意见,你应该使用 document.querySelector 在生命周期挂钩之后

    ngAfterViewInit() {
        (document.querySelector('.app-alerts') as HTMLElement).style.top = '150px';
    }
    
        2
  •  40
  •   Chris Stanley    8 年前

    我参加这个聚会迟到了,但不行!不要使用document.queryselector。这不是设计角度dom元素的方式!

    <div [ngStyle]="{'top.px': divStyle}">
    

    那么在你的组件中,你有

    ngAfterViewInit() {
      this.divStyle = 200; 
    }
    
    推荐文章