![](/img/trans.png)
[英]Rendering an Angular Component into the DOM without Component wrapper
[英]Angular 8 render component without extra wrapper element in the DOM
我正在嘗試將我的展示組件拆分為多個組件。 當我像這樣使用選擇器時:
@Component({
selector: 'app-video',
templateUrl: './video.component.html',
styleUrls: ['./video.component.scss']
})
它添加了一個包裝器“app-video”元素作為我組件的父元素,它打破了我的樣式。 因為我希望有這樣的 DOM 結構:
<div class="container">
<div>myComponentContent</div>
</div>
相反,我得到了這個:
<div class="container">
<app-video>
<div>myComponentContent</div>
</app-video>
</div>
我不需要這個包裝元素。 因為我希望我的組件必須是我的容器的直接子級。
解決這個問題的一種方法是我使用類選擇器或這樣的選擇器:
@Component({
selector: '[app-video]',
templateUrl: './video.component.html',
styleUrls: ['./video.component.scss']
})
哪個工作正常,但 tslint 抱怨它,因為根據 angular 樣式指南,它被認為是一種不好的做法:
https://angular.io/guide/styleguide#style-05-03
誰能告訴我實現這一目標的最佳和有效方法?
最好遵循最佳實踐。 因此,嘗試將樣式添加到全局樣式中以保持您的選擇selector: 'app-video'
選擇selector: 'app-video'
:
div app-video {
background: lightorange;
}
更新:
作為替代方案,您可以嘗試刪除選擇器,如下所示:
constructor(private el: ElementRef) {
}
ngOnInit() {
let yourNativeElement: HTMLElement = this.el.nativeElement,
parentElement: HTMLElement = nativeElement.parentElement;
// get all children and move them out of the element
while (nativeElement.firstChild) {
parentElement.insertBefore(nativeElement.firstChild, nativeElement);
}
// remove the empty element(the host)
parentElement.removeChild(nativeElement);
}
也許您應該考慮使用視圖封裝:無,在您的組件上https://angular.io/api/core/ViewEncapsulation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.