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

Jay*_*den 6 angular

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

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

        `})
    export class ChildComponent {
      Name = new FormControl('');
    }
Run Code Online (Sandbox Code Playgroud)

父组件:

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

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

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

dee*_*Dev 9

如果您通过模板中的选择器访问子项,则可以设置@ViewChild以访问其类,对于以下示例,使用其类作为类型。请务必导入@Viewchild和ChildComponent.

@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
      }
    }
Run Code Online (Sandbox Code Playgroud)

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