Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Angular@HostBinding inside指令设置和更新主机上的属性值_Angular_Angular2 Hostbinding - Fatal编程技术网

使用Angular@HostBinding inside指令设置和更新主机上的属性值

使用Angular@HostBinding inside指令设置和更新主机上的属性值,angular,angular2-hostbinding,Angular,Angular2 Hostbinding,那么,假设我有以下指令: <div foo></div> import { Directive, HostBinding } from '@angular/core'; @Directive({ selector: '[foo]' }); export class FooDirective { x: number; constructor() { this.x = 100; } @HostBinding('

那么,假设我有以下指令:

<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;
}
并在构造函数之外设置该值,则添加该值时不会出现任何问题

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

...

x: number = 100;

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

...

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

我发现了哪里出了问题

应该是这样的:

...

x: number = 100;

constructor() {}

...
<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); 
    }
}

从'@angular/core'导入{指令,HostBinding};
@指示({
选择器:“[foo]”
});
导出类指令{
@主机绑定('style.left.px')
x:数字=100;
构造函数(){
设置超时(()=>{
这个.x=200;
}, 2000); 
}
}
看起来我误解了这种方法的语法