angular - 如何重新运行作为输入属性传递给角度组件的方法?
问题描述
我需要将计算值传递给 Angular 组件。目前我正在这样做:
<component [value]="getCalculatedValue()"></component>
问题是计算值的基数每分钟都在变化,因此计算值也必须更新。
我如何告诉 Angular 为getCalculatedValue
它使用的每个组件再次运行该方法?
由于组件是外部组件,我更喜欢一种无需修改组件的方式。
解决方案
与其将函数(返回值)传递给组件,不如返回值。
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
}
}
推荐阅读
- unicode - 是否可以在 Keil uVision 5 中使用十六进制值超过 0xFF 的 unicode?
- python - SnowBoy 启动指令检测问题
- java - 如何从相同的 ControllerAdvice 方法返回对象或视图?
- c# - 从 ASP.NET 中的 gridview 下载文件时如何保存文件路径
- sql - 数据库查询以生成基于时间的图表
- nativescript - Nativescript 应用程序因“遇到未定义的提供程序!”而崩溃 在 IOS 上加载模块但在 Android 上工作之前
- mysql - MYSQL,包括空结果
- shell - 检查文件是否存在于 3 个不同的目录中并将它们移动到另一个
- curl - 在 VS2017、x64 中使用 curl
- sql - MIN DATE 有两个表和同一项目的多个实例