【问题标题】:Angular 2 - Child Component Not Inheriting Styling from Parent ComponentAngular 2 - 子组件不继承父组件的样式
【发布时间】:2016-12-15 23:33:33
【问题描述】:

我有一个使用子组件的父组件。我在父 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;
}

【问题讨论】:

    标签: html css angular typescript angular2-template


    【解决方案1】:

    将样式移动到子组件,并将类名从父组件传递给子组件。

    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 类以保持所有内容自包含。

    working plnkr

    【讨论】:

    • 感谢您的回答,但我正在实施的是,我有一个表格 div,当用户将鼠标悬停在 div 上时, 颜色会发生变化,当用户将鼠标悬停在 颜色和背景颜色再次发生变化。我已经在 Plunker 中进行了必要的更改。 plnkr.co/edit/gwcTi4QyZyFPtlgfY5Al?p=preview ,如果您能告诉我如何实现它,那就太好了。谢谢。
    • 好的,在你的父 div 中使用 (mouseover)="someFunction()" 并在你的父组件中实现 someFunction() ,它设置父类和子类,如我的回答。不要“硬编码”类名,在 someFunction() 中使用 ngClass 动态设置它们
    【解决方案2】:

    看起来你不能在 Angular2 中使用伪元素(悬停)。

    但是您可以制定自己的指令来更改悬停时的样式。
    查看本教程,该教程添加了一个用于突出显示悬停的属性指令。

    https://angular.io/docs/ts/latest/guide/attribute-directives.html#!#respond-to-user

    【讨论】:

    • Anchor 标签的悬停在 Angular 2 中有效。如果将 encapsulation: ViewEncapsulation.None 添加到父组件中,我的问题将有效,但它会更改所有样式。我在问是否有人知道任何其他解决方案?
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签