D
D
Drovosek012021-05-28 10:51:23
Angular
Drovosek01, 2021-05-28 10:51:23

How to add or forward a focus() event to a custom child component in Angular?

An Angular 11 project has a custom button component like this:

@Component({
  selector: 'ui-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.scss']
})
export class ButtonComponent extends ButtonBase {}


This button component is used in other components like so:
<ng-template [ngIf]="alert">
  <ui-button #myButton>
  </ui-button>
</ng-template>


The problem is that if I'm in the parent component, I take this button
@ViewChild('myButton') private myCustomButton: ElementRef<HTMLElement>;

And then I try to focus on it this.myCustomButton.nativeElement.focus();
Then an error appears in the console
ERROR TypeError: Cannot read property 'focus' of undefined


How can I make this code work correctly in the context of the described problem?
this.myCustomButton.nativeElement.focus();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2021-05-28
@Drovosek01

Create a method in the child component that will do the focus. And from the parent, pull this method asthis.myCustomButton.focus()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question