更新后为什么不触发onChanges

时间:2017-01-13 14:51:16

标签: javascript angular

我有以下父组件:

@Component({
    selector: 'hello-world',
    template: `
    <div>
        <private [text]="value"></private>
    </div>`
})

export class HelloWorldComponent {
    public value: number = 3;

    constructor() {
        setTimeout(function () {
            this.value = 5;
        }, 3000);
    }
}

和子组件:

@Component({
    selector: 'private',
    template: `<span>{{text}}</span>`
})

export class PrivateComponent implements OnChanges {
    @Input() public text: string;

    ngOnChanges(changes: SimpleChanges): void {
        console.log(changes.text.currentValue);
    }
}

ngOnChanges仅在3的预期值触发一次,但第二次没有触发5的值。为什么呢?

1 个答案:

答案 0 :(得分:1)

当您将值更改为5时,this引用您传递给setTimeout而不是HelloWorldComponent实例的匿名函数,您可以将构造函数更改为:

constructor() {
    var _self = this;
    setTimeout(function () {
        _self.value = 5;
    }, 3000);
}