简体   繁体   English

如何动态设置angular2组件标签的样式?

[英]How can i style an angular2 component tag dynamically?

New to angular2, so sorry if this is a stupid, easy question. angular2的新手,如果这是一个愚蠢而简单的问题,非常抱歉。

In angular1, i could create a simple directive like this, which will add a css class to the element, if a property of the model is true. 在angular1中,我可以创建一个像这样的简单指令,如果模型的属性为true,它将向该元素添加一个CSS类。

angular.module('app').directive('myDirective', function () {
    'use strict';

    return {
        restrict: 'E',
        templateUrl: '<div>Hello</div>',
        scope: {},
        bindToController: {
            myModel: '='
        },
        controller: function() {

        },
        controllerAs: 'ctrl',
        link: function(scope, element, attrs, ctrl) {
            if (myModel.addClass)
                element.addClass('col-xs-2');
        }
    };

});

How can i do this in angular2? 我该如何在angular2中做到这一点? Here is the component code for angular2, but i cannot find out how to add the class to the root element tag. 这是angular2的组件代码,但是我找不到如何将类添加到根元素标签的方法。

imports { Input } from '@angular/core';

@Component({
    selector: 'my-directive',
    template: `
        <div>Hello</div>
    `,
})

export class MyDirectiveComponent {
    @Input()
    myModel: Object;
}

我认为您正在寻找ngClass绑定...

<div [ngClass]="{'col-xs-2': myModel.addClass}">

Easy way (but not recommended ) would be 简单的方法(但不推荐)是

<div [style]="myStyle"></div>

and in your component 并在您的组件中

export class MyDirectiveComponent {
    @Input()
    myModel: Object;

   changeModel(col : number){
    this.myModel = 'col-xs-'+col; // Gives you col-xs-1 or 2 ....based on input
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM