【问题标题】:Using Angular @HostBinding inside directive to set and update attribute values on host使用 Angular @HostBinding inside 指令来设置和更新主机上的属性值
【发布时间】:2018-01-17 14:15:20
【问题描述】:

所以,假设我有以下指令:

<div foo></div>

import { Directive, HostBinding } from '@angular/core';

@Directive({
    selector: '[foo]'
});

export class FooDirective {
    x: number;

    constructor() {
        this.x = 100;
    }

    @HostBinding('style.left.px')
    styleLeftPx: number = this.x;
}

如果我按原样渲染它,它似乎不起作用,因为 this.x @HostBinding 初始化之后获取它的值。

因此,将上面的内容更改为更像这样:

...

x: number = 100;

constructor() {}

...

并且在构造函数之外设置该值,该值被添加没有问题。

但是,如果我尝试在任何时候更改该值,例如超时:

...

x: number = 100;

constructor () {
    setTimeout(() => {
        this.x = 200;
    }, 2000)
}

...

主机属性不会更新为新值。初始初始化后这里没有数据绑定吗?堆栈上有很多答案讨论如何使用@HostBinding 设置 attr 的初始值,但是在 init 之后更改该值呢?

【问题讨论】:

    标签: angular angular2-hostbinding


    【解决方案1】:

    我知道我哪里错了。

    应该是这样的:

    <div foo></div>
    
    import { Directive, HostBinding } from '@angular/core';
    
    @Directive({
        selector: '[foo]'
    });
    
    export class FooDirective {
        @HostBinding('style.left.px')
        x: number = 100;
    
        constructor() {
            setTimeout(() => {
                this.x = 200;
            }, 2000); 
        }
    }
    

    看来我误解了这种方法的语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2018-04-30
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多