假设这里有一个简单的Angular组件MyComponent
。
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: '[my-component]',
template: `
<div class="my-component-child">
<ng-content></ng-content>
</div>`,
encapsulation: ViewEncapsulation.None,
host: { 'class': 'my-component' }
})
export class MyComponent {
constructor() { }
}
此组件随后在ParentComponent
中使用。
因为MyComponent
封装设置为无,我可以样式它的.my-component
类从ParentComponent
,但我不能样式.my-component-child
,除非我设置ParentComponent
封装为无,我喜欢为了避免。
我怎么能样式.my-component-child
或解决它(不使用根styles.scss
或::ng-deep
或父的封装设置为none)?
如果在这些条件下不可能做到以上几点,那么Angular有没有什么实践或策略来处理这种情况(我对Angular还是相当陌生的)?
解决方案是将CSS类传递给子组件。你的组件看起来像这样:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: '[my-component]',
template: `
<div class="my-component-child" [ngClass]="extraClasses">
<ng-content></ng-content>
</div>`,
encapsulation: ViewEncapsulation.None,
host: { 'class': 'my-component' }
})
export class MyComponent {
constructor() { }
@Input() extraClasses = ""
}
然后将额外的类传递给子类:
<my-component [extraClasses]="flex"></my-component>
当然,在这个结构中,您需要在全局上下文中定义类。
如果你仍然不想全局声明任何类,那么另一种方法是将你想要的选项传递给子组件,并让子组件根据给定的选项样式化自己。