【问题标题】:Styles are not applied to HTML element after dynamically inserted to DOM - Angular动态插入到 DOM 后,样式不会应用于 HTML 元素 - Angular
【发布时间】:2021-06-16 21:58:56
【问题描述】:

我想将“i”元素作为子元素添加到 HTMLDivElement 但样式不会应用于新插入的“i”元素。

如何确保对新添加的“i”元素应用相同的样式? 我想应用我在 scss 文件中为新元素设置的样式。 (当我在 .ts 文件中插入新元素时,我可以使用 JS(TS) 设置相同的样式,但我打算使用 scss/css 样式,有什么方法可以将 scss/css 样式用于新添加的元素?)

住宿查看数据.html

<div class="star-rating" #starRating>
  <i class="bi bi-star-fill"></i> <!-- styles are applied to this element successfully -->
</div>

accommodation-view-data.component.scss

i{
  font-size: 1.6rem;
  padding: 0 0.25rem ;
  color: #ffbe0f;
}

accommodation-view-data.component.ts

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-accommodation-view-data',
  templateUrl: './accommodation-view-data.component.html',
  styleUrls: ['./accommodation-view-data.component.scss']
})
export class AccommodationViewDataComponent implements OnInit, AfterViewInit {

  @ViewChild('starRating')
  starRatingElem!: ElementRef;

  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    /* When I append the the new element to the DOM,
    * the styles that I have set in the scss file, are not applied for the new element */
    const starIconElement = document.createElement('i');
    starIconElement.classList.add('bi');
    starIconElement.classList.add('bi-star-fill');
    (this.starRatingElem.nativeElement as HTMLDivElement).append(starIconElement);
  }

}

【问题讨论】:

    标签: javascript css angular typescript sass


    【解决方案1】:

    这是一种正常行为,当您编写集成在 styleUrls 中的样式时,每个单独的类都被重新设计为特定于组件,它是样式范围(注意下面屏幕截图中的 i[ng-content-lep-c52])。

    因此,不建议像您那样在 dom 中添加元素,而是更喜欢通过 ngIf 或此处使用 ngFor 来切换它,否则您将很难尝试使其动态并与组件模型。

    正如您在此屏幕截图中看到的那样,第一个元素与作用域样式正确匹配,而新元素则没有。

    不推荐和弃用:要绕过它,您可以使用 ::ng-deep 伪类来使样式全局化,因此被范围样式覆盖,如您在此屏幕截图中看到的那样stackblitz.

    您可以在 angularhere
    中找到更多关于样式的信息

    【讨论】:

    • 感谢您的解释。
    • @Dhanusha_Perera07 如果此答案满足您的需求,您可以投票并接受它,谢谢
    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2021-07-27
    相关资源
    最近更新 更多