我有一个父组件:
<parent></parent>
我想用子组件填充这个组:
<parent>
<child></child>
<child></child>
<child></child>
</parent>
父模板:
<div class="parent">
<!-- Children goes here -->
<ng-content></ng-content>
</div>
子模板:
<div class="child">Test</div>
由于父组件和子组件是两个独立的组件,它们的样式被锁定在自己的范围内。
在我的父组件中,我尝试这样做:
.parent .child {
// Styles for child
}
但是.child样式没有应用到子组件。
我尝试使用styleUrls将父组件的样式表包含到子组件中,以解决范围问题:
// child.component.ts
styleUrls: [
'./parent.component.css',
'./child.component.css',
]
但这并没有帮助,我还尝试了另一种方法,将子样式表取到父样式表中,但这也没有帮助。
那么,如何样式包含在父组件中的子组件呢?
我也有这个问题,不想使用弃用的解决方案
所以我最后得出:
在parrent
<dynamic-table
ContainerCustomStyle='width: 400px;'
>
</dynamic-Table>
子组件
@Input() ContainerCustomStyle: string;
在child In HTML div中
<div class="container mat-elevation-z8"
[style]='GetStyle(ContainerCustomStyle)' >
在代码中
constructor(private sanitizer: DomSanitizer) { }
GetStyle(c) {
if (isNullOrUndefined(c)) { return null; }
return this.sanitizer.bypassSecurityTrustStyle(c);
}
作品像预期的那样,不应该被弃用;)
实际上还有一个选择。这样比较安全。你可以使用ViewEncapsulation。但把你所有的组件样式放到它的标签(又名选择器)。但无论如何,总是喜欢一些全局风格加上封装风格。
下面是Denis Rybalka的例子:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'parent',
styles: [`
parent {
.first {
color:blue;
}
.second {
color:red;
}
}
`],
template: `
<div>
<child class="first">First</child>
<child class="second">Second</child>
</div>`,
encapsulation: ViewEncapsulation.None,
})
export class ParentComponent {
constructor() { }
}