gpt4 book ai didi

angular - 从父组件调用多个子方法

转载 作者:行者123 更新时间:2023-12-04 16:06:19 25 4
gpt4 key购买 nike

我正在尝试使用 ViewChild 从父组件调用子方法:

...

export class Parent {
@ViewChild(ProfileImageComponent) profileImage: ProfileImageComponent;
...

updateProfile() {
...
this.profileImage.updateAvatar();
}
}

问题是这只适用于父 View 中的第一个子组件实例:

...
<profile-image></pofile-image> <!-- only this one gets updated -->
...
<profile-image></pofile-image>
...
<profile-image></pofile-image>
...

如何调用每个 profileImage 子方法以便更新所有内容?

最佳答案

使用 @angular/core 中的 @ViewChildren 来获取对组件的引用。

模板:

<profile-image #profile></pofile-image>
<profile-image #profile></pofile-image>
<profile-image #profile></pofile-image>

组件:

import { ViewChildren, QueryList } from '@angular/core';

@ViewChildren('profile') components:QueryList<ProfileImage>;

ngAfterViewInit(){
// call method
this.components.forEach(ProfileImage => {
ProfileImage.updateAvatar();
});
}

关于angular - 从父组件调用多个子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48723453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com