【问题标题】:How to reset a field in child component from parent component - angular如何从父组件重置子组件中的字段 - 角度
【发布时间】:2019-02-13 18:30:17
【问题描述】:

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

    @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..
      }
    }

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

【问题讨论】:

  • 你使用的是表单控件,那么就使用reset
  • @AJT_82 两者都是不同的组件,所以我怎样才能从父组件重置..
  • 我看你的代码有点太快了。那么,它们是如何通过路由或父级中的子标签相互关联的呢?但无论如何,你的答案就在这里:angular.io/guide/component-interaction
  • 视情况而定...这也有帮助:angular.io/api/core/ViewChild

标签: angular


【解决方案1】:

如果您通过模板中的选择器访问子级,您可以设置@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
      }
    }

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 2019-04-16
  • 2023-04-09
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多