首页 文章

Angular 2组件样式本身可以吗?

提问于
浏览
8

在Angular 2中,您可以在组件的模板中包含样式表 . 由于Angular 2的View Encapsulation,样式仅适用于包含元素 .

有没有办法设置组件的主标签样式而不放置周围的 <div class="component-wrapper"></div>

示例plnkr:http://plnkr.co/edit/rANAsR1h9ERBIZV6wuJ8

它有一个外部css文件,为 <app> 标签添加边框和填充,模板尝试设置背景颜色 .

1 回答

  • 19

    你有两个选择

    • 使用 host 属性
    @Component({
        selector : 'my-component',
        host : {
            '[style.color]' : "'red'", 
            '[style.background-color]' : 'backgroundColor'
        }
    })
    class MyComponent {
        backgroundColor: string;
        constructor() {
            this.backgroundColor = 'blue';
        }
    }
    
    • 使用 styles 属性和:host
    @Component({
        selector : 'my-component',
        styles : [`
            :host {
                color: red;
                background-color: blue;
            }
        `]
    })
    class MyComponent {}
    

    Note 使用 :hostViewEncapsulation.None 时有一个odd behavior .

    这是一个plnkr,其中有两个替代方案的简单示例 .

相关问题