angular - Angular 没有通过 ChangeDetectorRef 运行变更检测
问题描述
我有一个带有输入变量的子组件,例如“名称”。它通过 Parent 组件的数据绑定具有一些初始值。现在,当我从子组件本身内部更改“名称”的值时,Angular 不知道。我如何让 Angular 知道这个变化?
根据我在网上阅读的内容,我尝试使用ChangeDetectorRef.detectChanges()
或ChangeDetectorRef.markForCheck()
它似乎不起作用。我想我错过了一些东西。
这是此问题的 stackblitz 链接。如果您从子组件中更改名称,然后再次尝试从父组件更改名称,它不会更改,因为 Angular 仍然认为它绑定到父组件之前提供的值。但是我从子组件内部更改了它。我该如何解决?
解决方案
ngOnChanges
ngOnChanges 生命周期仅在有界输入属性值与当前值不同时运行
例子:
OnChanges(changes: SimpleChanges){
if(changes.name.currentValue !== changes.name.previousValue){
//if the bound value is diffrent from currentValue then ngOnChanges will be triggered
}
使用ngDoCheck生命周期钩子。
执行更改检测的回调方法,在默认更改检测器运行后调用。
推荐阅读
- c++ - 这个while循环如何整理指针?
- javascript - Html css获取输入值并将其保存在数组中
- node.js - VSC 终端中的“CLIENT_MISSING_INTENTS”-discord.js v13
- css - 有没有办法让重复列缩小以适应 CSS 网格中的内容?
- javascript - 获取在 Node.js 中声明函数的文件
- discord - 不和谐机器人文件的组织
- php - 在 PHP 中比较两个字符串的问题
- windows - WSL 和串口
- opencv - 三角剖分 3D 点导致扭曲(抛物面)图的原因可能是什么?尝试使用 SFM 执行 3D 重建
- python - 如何解决此问题“ModuleNotFoundError: No module named 'torch.tensor'”