Search code examples
angulartypescriptionic-framework

Access Child component html element from the parent component


attendees.component.html (Parent)

 <app-add-guest (guestUserChange)="addGuest($event)"></app-add-guest>

add-guest.component.html (Child)

<form [formGroup]="form">
  <ion-row>
    <ion-col>
      <ion-item>
        <ion-label position="stacked" color="light">Guest name</ion-label
        >

        <ion-input // this input here
          formControlName="guestName"
          color="light"
          type="text"
          placeholder="Guest name"
       >
        </ion-input>
      </ion-item>
    </ion-col>
  </ion-row>
</form>

Can you tell me how to access ion-input from the parent component? Because I need to setfocus on that input within the parent component.

I saw a lot of examples of how to access the child component method using @ViewChild. But not for my use case above.


Solution

  • If we're following proper separation of concerns, the parent shouldn't know anything about the template of the child. Add a method to the child that focuses the input and have the parent call this method when appropriate.

    @Component({
        /* ... */
        selector: 'app-add-guest',
        template: `
            <!-- ... -->
            <ion-input // this input here
              formControlName="guestName"
              color="light"
              type="text"
              placeholder="Guest name"
            >
            <!-- ... -->
        `,
    })
    export class AddGuestComponent {
      @ViewChild(IonInput) guestNameInput?: IonInput;
    
      focusInput(): void {
        this.guestNameInput?.setFocus();
      }
    }
    
    @Component({
        /* ... */
        template: `<app-add-guest></app-add-guest>`,
    })
    export class AttendeesComponent implements AfterViewInit {
      @ViewChild(AddGuestComponent) child?: AddGuestComponent;
    
      ngAfterViewInit(): void {
        this.child?.focusInput();
      }
    }