我在使用Angular router-oulet时遇到了麻烦,因为它为DOM添加了新元素,它影响了应用的CSS规则,因为它破坏了某些元素的父子关系。这是我的意思的一个例子:
正如您所看到的,在每个<router-outlet></router-outlet>
之后是插入的组件选择器(代码中的app-fwc-dashboard-main
和app-fwc-policy-main
),并且所有组件模板标记都位于其下方。这使得有些CSS规则未应用且布局中断。
我一直在比较从一个版本到另一个版本的代码,我意识到组件选择器有类ng-star-inserted
所以我试图添加缺少的CSS规则,如下所示:
.grid-y > .ng-star-inserted > .auto, .grid-y > .ng-star-inserted > .shrink {
height: auto;
}
.grid-y > .ng-star-inserted > .cell {
width: auto;
}
(etc)
但是,由于某些原因我找不到,它没有用。所以我的问题是:有没有办法告诉Angular路由器插座只注入组件模板标记并避免添加选择器?
或者对此问题还有其他建议吗?提前致谢!
我不认为这是可能的。
我认为你有两种可能的解决方案:
>
选择器。如果这些对您不起作用,我建议以一种更容易使用的方式重写代码。
您可以使用Component的属性选择器。在样式中使用@HostBinding
和css选择器:host
添加类。
@Component({
selector: '[attributeSelector]',
template: 'red text',
styles: [':host {color: red}'],
})
class A {
@HostBinding('class') class = 'boundClass';
}
在这种情况下,router-outlet
将创建类似的东西
<router-outlet></router-outlet>
<div attributeSelector class="boundClass" nghost_1>red text</div>
Ilia Volk的回答向我展示了找到解决方案的正确途径。我将组件选择器更改为:
selector: '[app-vpn-component].grid-y.medium-grid-frame',
这样,渲染的标记是:
<div app-fwc-vpn-main="" class="grid-y medium-grid-frame ng-star-inserted">
...
</div>
现在布局看起来和以前一样。