gpt4 book ai didi

angular - 如何从父组件重置子组件中的字段 - Angular

转载 作者:太空狗 更新时间:2023-10-29 17:51:02 27 4
gpt4 key购买 nike

我在从父组件重置子组件中的字段时遇到了一些困惑。我在子组件中有一个字段,当在父组件中调用函数时,子字段应该重置。子组件:

    @Component({
selector: 'my-app',
template: `
<input type="text" placeholder="Type your name..." [formControl]="Name"/>

`})
export class ChildComponent {
Name = new FormControl('');
}

父组件:

@Component({
selector: 'my-parent-app',
template: `

`})
export class ParentComponent {
resetName(){
// Here I need to reset my child component field..
}
}

如果有人有想法,请你帮我理解..

最佳答案

如果您通过模板中的选择器访问子项,您可以设置一个 @ViewChild获得对其类的访问权限,对于以下示例,该类如下所示,使用其类作为类型。请务必导入 @ViewchildChildComponent

@Component({
selector: 'my-parent-app',
template: `
<my-app #component-child></my-app>
`})
export class ParentComponent {

@ViewChild('component-child') childComponent: ChildComponent;

public resetName(): void
{
console.log(this.childComponent) // should see everything within the class.
this.childComponent.name.reset(); // should reset the form in child component
}
}

如果遇到任何问题,请发表评论。

关于angular - 如何从父组件重置子组件中的字段 - Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677088/

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