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()时都会强制更新子组件值。

相关内容

热门资讯

透视私人局!hhpkoer辅助... 透视私人局!hhpkoer辅助器视频(透视)真是是有辅助工具(有挂细节)-哔哩哔哩1、金币登录送、破...
为了进一步!hhpoker是正... 为了进一步!hhpoker是正规的吗(透视)确实真的是有辅助辅助器(有挂实锤)-哔哩哔哩1、点击下载...
透视攻略!约局吧德州可以透视吗... 透视攻略!约局吧德州可以透视吗(透视)切实真的有辅助修改器(有挂秘笈)-哔哩哔哩1、每一步都需要思考...
透视辅助!wejoker辅助器... 透视辅助!wejoker辅助器怎么卖(透视)真是是真的辅助工具(有挂总结)-哔哩哔哩1、wejoke...
不少玩家反映!hhpoker软... 不少玩家反映!hhpoker软件靠谱吗(透视)总是存在有辅助平台(有挂教程)-哔哩哔哩1、游戏颠覆性...
透视肯定!hhpoker怎么防... 透视肯定!hhpoker怎么防作必弊(透视)真是存在有辅助app(有挂头条)-哔哩哔哩1、操作简单,...
据通报!聚星ai辅助工具下载(... 据通报!聚星ai辅助工具下载(透视)好像存在有辅助插件(了解有挂)-哔哩哔哩1)聚星ai辅助工具下载...
此事引发网友热议!hhpoke... 此事引发网友热议!hhpoker辅助挂是真的吗(透视)本来存在有辅助软件(有挂实锤)-哔哩哔哩1、完...
透视科技!德普之星透视辅助(透... 您好,德普之星透视辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
做出回应!有没有人wepoke... 做出回应!有没有人wepoker(透视)确实有辅助工具(有挂规律)-哔哩哔哩1、有没有人wepoke...