我有一个使用子组件的父组件。我在 Parent Css 文件中编写了必要的样式,当我们将鼠标悬停在 div 上时,样式会相应地发生变化。子组件未访问父组件的样式类。
有一个解决方案可以做到这一点,使用 encapsulation: ViewEncapsulation.None
,但是当我使用它时,我的整个样式都被打乱了。
还有其他方法吗?
Plunker 示例:http://plnkr.co/edit/gwcTi4QyZyFPtlgfY5Al?p=preview
子组件:
import {Component} from '@angular/core';
@Component({
selector:'testapp',
template: `
<a href="https://www.google.com">Google</a>
`
})
export class TestApp{
}
父组件: HTML代码:
<div class="container">
<div class="test">
<testapp></testapp>
</div>
</div>
父组件:CSS 代码:
.container{
font-family:sans-serif;
font-size:18px;
border: 1px solid black;
}
.test{
width:50%;
background-color:#f0f5f5;
}
.container:hover .test{
background-color:#e6ffe6;
}
.container:hover .test:hover{
background-color:#ffffe6;
}
.container .test a {
color: red ;
}
.container .test a:hover {
color:green;
}
最佳答案
将样式移动到子组件并将类名从父组件传递给子组件。
import {Component} from '@angular/core';
@Component({
selector:'testapp',
template: `
<a [ngClass]="anchorClass" href="https://www.google.com">Google</a>
`,
styles: [`
a.red-green-anchor {color:red;}
a.red-green-anchor:hover {color:green;}
a.orange-blue-anchor {color:orange;}
a.orange-blue-anchor:hover {color:blue;}
`]
})
export class TestApp{
@Input() anchorClass: string;
}
父 HTML
<div class="container">
<div class="test">
<testapp [anchorClass]="'red-green-anchor'"></testapp>
</div>
</div>
您尝试执行此操作的方式是将父项与子项紧密耦合,而不是将所有内容都包含在内。将样式移至子项可使子项保持独立,任何 parent 都可以决定设置哪个子 css 类以保持一切独立。
关于html - Angular 2 - 子组件不从父组件继承样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38858903/