首页 > 解决方案 > 如何重新运行作为输入属性传递给角度组件的方法?

问题描述

我需要将计算值传递给 Angular 组件。目前我正在这样做:

<component [value]="getCalculatedValue()"></component>

问题是计算值的基数每分钟都在变化,因此计算值也必须更新。

我如何告诉 Angular 为getCalculatedValue它使用的每个组件再次运行该方法?

由于组件是外部组件,我更喜欢一种无需修改组件的方式。

标签: angular

解决方案


与其将函数(返回值)传递给组件,不如返回值。

HTML:

<component [value]="value"></component>

TS:

export class CurrentComponent implements OnInit {
    value: any;

    ngOnInit() {
        this.value = getCalculatedValue();

        // insert functionality to recalculate value on either a timer, Observable, etc...
    }
}

输入中的函数也会在更改检测时重新运行

@Component({
    selector: 'app-current',
    templateUrl: './current.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class CurrentComponent implements OnInit {

    constructor(private cd: ChangeDetectorRef) { }

    ngOnInit() {
        // call this.cd.detectChanges() when you want an update
    }

}

推荐阅读