【问题标题】:how to access the class css properties from an attribute directive associated with the same element如何从与同一元素关联的属性指令访问类 css 属性
【发布时间】:2017-10-16 10:29:23
【问题描述】:

这是组件模板

template: `<h1 class = "dragStyle" [drag] = "true">DRAG THIS ELEMENT</h1>`,
styles : [`
    .dragStyle{
        margin : 12px;
    }`
]    

这里是[拖动]属性指令的构造函数-

constructor(
    private _el: ElementRef, 
    private _renderer : Renderer,
    @Attribute('class') type : string) {
        console.log(type);

我需要访问与 dragStyle 类关联的边距属性的值以进行一些计算。

【问题讨论】:

    标签: javascript css angular


    【解决方案1】:

    我不知道你要做什么'将css类对象注入构造函数'是否可行。但是,既然您只需要计算的 css 属性,为什么不使用 getComputedStyle() 呢?

    在你的例子中,

    @Directive({
      selector:'[drag]' 
    })
    export class DragDirective{
      @Input() drag:boolean;
      constructor(
        private _el: ElementRef, 
        private _renderer : Renderer,
        @Attribute('class') type : string) {
            console.log(type);
      }
      ngOnInit(){
        let margin = getComputedStyle(this._el.nativeElement).getPropertyValue('margin');
        console.log(margin);
      }
    }
    

    这是plunker

    【讨论】:

    • @shiv 很高兴我能帮上忙
    猜你喜欢
    • 2016-10-26
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多