Angular 8渲染组件在DOM中没有额外的包装器元素 [英] Angular 8 render component without extra wrapper element in the DOM
问题描述
我正在尝试将我的演示文稿组件拆分为多个组件.当我这样使用选择器时:
I am trying to split my presentational component to multiple components. When I use selector like this:
@Component({
selector: 'app-video',
templateUrl: './video.component.html',
styleUrls: ['./video.component.scss']
})
它将包装器"app-video"元素添加为组件的父级,这破坏了我的样式.因为我希望具有这样的DOM结构:
it adds a wrapper "app-video" element as a parent of my component and it breaks my styling. Because I expect to have DOM structure like this:
<div class="container">
<div>myComponentContent</div>
</div>
相反,我得到了:
<div class="container">
<app-video>
<div>myComponentContent</div>
</app-video>
</div>
我不需要这个包装元素.因为我希望组件必须是容器的直接子代.
I don't need this wrapper element. Because I expect that my component must be the direct child of my container.
解决此问题的一种方法是,我使用类选择器或类似的选择器:
one way that solves this problem is that I use either a class selector or the selector like this:
@Component({
selector: '[app-video]',
templateUrl: './video.component.html',
styleUrls: ['./video.component.scss']
})
哪个可以很好地工作,但是tslint抱怨它是因为根据角度样式指南,它被认为是不好的做法:
Which works fine, but tslint complains about it because it is considered as a bad practice according to angular style guides:
https://angular.io/guide/styleguide#style-05-03
有人能告诉我实现这一目标的最佳和有效方法吗?
Can anyone tell me the best and valid way to achieve this?
推荐答案
最好遵循最佳做法.因此,请尝试将样式添加到全局样式中,以保持选择器 selector:'app-video'
:
It is better to follow best practices. So try to add style into global style to keep your selector selector: 'app-video'
:
div app-video {
background: lightorange;
}
更新:
作为替代方案,您可以尝试删除选择器,如下所示:
As an alternative, you can try to remove selectors something like this:
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);
}
这篇关于Angular 8渲染组件在DOM中没有额外的包装器元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!