angular组件当前组件host动态添加样式

angular项目中,我们都知道可以用 

[class.className]="variable" 

或者 

[style.styleName]="styleValue" 

这2种方法给组件中的元素添加动态样式。

但是如果给当前组件的标签添加动态样式呢,如下比如要给<app-about></app-about>添加动态样式。

import { Component } from '@angular/core';

@Component({

    selector: ‘app-about’,

    styleUrls: ['./about.component.scss'],

    templateUrl: './about.component.html'

})

export class AboutComponent {

    open = false;

}

这就需要用到host或者hostBinding,有下面3中方法:

参考:

http://angular.cn/api/core/HostBinding

https://zhuanlan.zhihu.com/p/347464587

angular 控件css_Angular5给组件本身的标签添加样式class的方法

https://stackoverflow.com/questions/35168683/hostbinding-with-a-variable-class-in-angular

1.使用@component的host属性, 注意属性的值默认为变量,如果直接使用属性值,需要加字符串单引号或者双引号,变量直接在组件里定义即可

@Component({

    selector: ‘app-about’,

    host: {

            '[style.color]' : "'red'",

            '[style.background]' : "bgColor"

            '[class.myClass]' : "showMyClass"

    }

    styles: [` 

        .myClass {

                    color: orange;

            }

    `]

})

Class AboutComponent {

        bgColor = "yellow";

        showMyClass = true;

}

2 使用host样式,这样能加样式,但是就是加不了动态样式,但是注意最后tips,还会有用的。

@Component({

    selector: ‘app-about’,

    styles: [` 

        :host {

                color: orange;

            }

    `]

})

3.使用hostBinding给当前组件绑定class,然后在style里定义class即可

Class AboutComponent {

        @HostBinding('class.className')  get  className () {return showMyClass};

}

Tips:

如果在styles里定义的class加到DOM了,但是样式不起作用,不妨加:host试试,也就是定义的class从host开始找。因为我加了也遇到了class有了但是样式不起作用的问题。

参考的这个文章https://zhuanlan.zhihu.com/p/347464587

比如:

:host.myClassName

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Angular 2+ (Now 5.0) 应用程序使用的是常规CSS样式,意思就是说CSS标准中的所有东西都可以直...
    山哥Samuel阅读 3,551评论 0 0
  • Theming your custom components 主体化自定义的组件 In order to styl...
    王义杰阅读 917评论 0 1
  • 在前面的问题汇总的第四个里,介绍过angular2的组件投影,也就是我们在使用组件的时候,父组件可以用属性...
    avery1阅读 1,513评论 0 0
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,629评论 28 53
  • 信任包括信任自己和信任他人 很多时候,很多事情,失败、遗憾、错过,源于不自信,不信任他人 觉得自己做不成,别人做不...
    吴氵晃阅读 6,242评论 4 8