Home > Blockchain >  How to focus an input field that is in another component?
How to focus an input field that is in another component?

Time:10-12

In Component1 I have the following form:

<form [formGroup]="formMain">
  <mat-form-field appearance="legacy">
    <mat-label>Title</mat-label>
    <input id="title" matInput formControlName="title">
  </mat-form-field>
</form>

In Component2 I have the following hyperlink:

<a id="error-title" (click)="jumpToError($event)" href="">Title</a> is not specified.
jumpToError(event: Event): void {
  event.preventDefault();
  if ((event.target as Element).id == 'error-title') {
    // Jump to error
  }
}

If the user clicks on that hyperlink, I want the input field to be focused. I don't know how to focus it since it is in another component. How do I do this?

CodePudding user response:

  1. modify Component1

<input id="title" matInput #search formControlName="title">

@ViewChild('search') searchElement: ElementRef;

focus(){
    this.searchElement.nativeElement.focus();
}
  1. Add output to Component2
@Output() jumpToError = new EventEmitter();
  1. in parent component

@ViewChild(Component1) private component1: Component1;

focus() {
    this.component1.focus();
}

<component2 (jumpToError)="focus()">

  • Related