如何解决动态插入到 DOM 后,样式不会应用于 HTML 元素 - Angular
我想添加一个“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>
住宿-视图-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);
}
}
解决方法
这是一种正常行为,当您编写集成在 styleUrls 中的样式时,每个类都会重新设计为特定于组件,即样式范围(请注意下面屏幕截图中的 i[ng-content-lep-c52]
)。
因此,不建议像您那样在 dom 中添加元素,而是更喜欢通过 ngIf 或此处使用 ngFor 来切换它,否则您将很难尝试使其动态并使用组件模型。
就像您在此屏幕截图中看到的那样,第一个元素与作用域样式正确匹配,而新元素则没有。
不推荐和弃用:要绕过这一点,您可以使用 ::ng-deep
伪类使样式全局化,从而被作用域样式覆盖,如您在此屏幕截图中所见从此stackblitz。
您可以在 angular here
中找到有关样式的更多信息