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

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

问题描述

在给定的Attribute指令示例(即增加外观/行为的指令)中,我们在host元素上设置了一个非常简单的样式设置.例如

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天全站免登陆