Angular的子组件在父组件的值发生更改时不会变化。
创始人
2024-10-24 11:32:21
0

可能是因为子组件没有及时更新其值,为了解决这个问题,可以使用@Input装饰器以在子组件中获取和响应父组件被传递的数据。通过这种方式,可能会出现子组件自动更新其值的情况。示例如下:

父组件HTML:

父组件TS:

myValue: string = 'Hello World!';

子组件TS:

import { Component, Input } from '@angular/core';

@Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent { @Input() parentValue: string; constructor() { } }

子组件HTML:

Parent Value: {{parentValue}}

现在,每当父组件的值更改时,都会相应地在子组件中更新其值。

如果上述方法仍未解决问题,那么可以尝试使用Angular的变更检测策略来强制更新子组件,如下所示:

父组件TS:

import { Component, ChangeDetectorRef } from '@angular/core';

@Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent { myValue: string = 'Hello World!'; constructor(private cd: ChangeDetectorRef) {}

updateValue() { this.myValue = 'New Value!'; this.cd.detectChanges(); } }

此时,每次调用cd.detectChanges()时都会强制更新子组件值。

相关内容

热门资讯

透视透视!德普之星怎么作弊,w... 大家肯定在之前wepoker辅助器安装包或者wepoker辅助器安装包中玩过透视透视!德普之星怎么作...
透视插件!wpk透视表,德普之... 透视插件!wpk透视表,德普之星透视辅助插件,必备教程(先前是真的有挂)是一款可以让一直输的玩家,快...
透视总结!aapoker辅助工... 透视总结!aapoker辅助工具免费下载,wepoker私人局外卦,必胜教程(真是真的有挂),亲,有...
透视线上!德普之星透视辅助,智... 透视线上!德普之星透视辅助,智星菠萝可以辅助吗,新2025教程(果然存在有挂);致您一封信;亲爱智星...
透视安装!德普之星辅助器,hh... 相信很多朋友都在电脑上玩过德普之星辅助器吧,但是很多朋友都在抱怨用电脑玩起来不方便。为此小编给大家带...
透视规律!wepoker辅助透... 透视规律!wepoker辅助透视软件,拱趴大菠萝有挂吗,科技教程(确实是有挂) 科技详细教程;Q群1...
透视ai!wpk脚本是什么,w... 透视ai!wpk脚本是什么,wepokerplus开挂,必胜教程(素来真的有挂);(需添加指定Q群1...
透视了解!wepoker透视脚... 1、透视了解!wepoker透视脚本苹果,wepoker透视最简单三个步骤,技巧教程(总是真的有挂)...
透视挂透视!wepoker透视... 这是一款非常优秀的wepoker透视脚本安卓 ia辅助检测软件,能够让你了解到wepoker透视脚本...
透视透视!hhpoker万能辅... 透视透视!hhpoker万能辅助器,拱趴大菠萝有挂吗,我来教教你(果然真的有挂);玩家必备必赢加哟《...