Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a field in child component from parent component - angular

Tags:

angular

I am facing bit confusion to reset a field in child component from parent. I'm having a field in child component, when calling a function in parent component the child field should reset. Child component:

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

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

Parent component:

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

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

If any one have idea, could you please help me to understand..

like image 681
Jayden Avatar asked Feb 13 '19 18:02

Jayden


1 Answers

If you access the child through its selector within the template you can set up a @ViewChild to gain access to its class which would look like below for the following example, using its class for the type. Be sure to import @Viewchild and 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
      }
    }

Drop a comment if you face any trouble.

like image 199
Dince12 Avatar answered Oct 16 '22 13:10

Dince12