我有一个使用子组件的父组件。我在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;
}
答案 0 :(得分:2)
将样式移动到子组件,并将类名从父项传递给子项。
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>
您尝试这样做的方式是将父级与子级紧密耦合,而不是将所有内容保持为自包含状态。将样式移动到子项可以使子项自包含,任何父项都可以决定将哪个子css类设置为自包含。
答案 1 :(得分:0)
看起来你可以使用带有Angular2的伪元素(悬停)。
但是你可以制定自己的指令来在悬停时改变样式 查看本教程,该教程添加了一个属性指令,用于突出显示悬停。
https://angular.io/docs/ts/latest/guide/attribute-directives.html#!#respond-to-user