指令中的 Angular2 样式 [英] Angular2 Styles in a Directive

查看:33
本文介绍了指令中的 Angular2 样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定的属性指令示例(即添加外观/行为的指令)中,我们对宿主元素的样式进行了相当简单的设置.例如

In the given examples of Attribute directives (i.e. a directive to add appearance/behaviour), we have a fairly simple setting of a style on the host element.. e.g.

import {Directive, ElementRef } from 'angular2/core';
@Directive({
    selector: '[myHighlight]'
})
export class HighlightDirective {
    constructor(element) {
       element.nativeElement.style.backgroundColor = 'yellow';
    }

static get parameters(){
    return [[ElementRef]];
}

我可以使用样式而不是设置样式吗?例如

Rather than setting the style, can i use a styles instead? e.g.

@Directive({
    selector: '[myHighlight]',
    styles: [':host { background-color: yellow; }']
})

这似乎对我不起作用?

我正在做一些稍微复杂的事情,这导致了相当多的单一代码,设置了很多样式,使用了 AnimationBuilder 等.在我看来,将它分离成类和动画会更好一个 CSS.

I'm doing something slightly more complex which has led to a fair amount of monolothic code, setting lots of styles, using AnimationBuilder etc etc. feels to me like it would be much better to seperate this out into classes and animations in a CSS.

ViewEncapsulation = 模拟/默认是否重要?

ViewEncapsulation = emulated/default if that matters?

推荐答案

您可以使用主机绑定来绑定样式属性:

You can use host binding to bind to style attributes:

@Directive({
    selector: '[myHighlight]',
    host: {
      '[style.background-color]': '"yellow"',
    }
})

@Directive({
    selector: '[myHighlight]',
})
class MyDirective {
  @HostBinding('style.background-color')
  backgroundColor:string = 'yellow';
}

这篇关于指令中的 Angular2 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆