简体   繁体   中英

Angular Button click with Template reference variable is not working

I have two html buttons in angular application. Not sure what is causing issue.

Stackblitz code here

First button is as below: I have button click event on 1st button with template reference variable

<button (click)="accessButton(b)" #b >Click me!</button>

Second button is as below: Problem:I have focusout event and want to set the focus to 1st button once user click on tab when the focus is on 2nd button. But for some reason template reference variable is getting error to set focus to first button.

<button (click)="onYes()" (focusout)="onFocusOut($event)" [disabled]="isDisabled">Yes</button>

Typescript file:

@ContentChild('onNo', { static: false }) elOnNo: ElementRef;
  accessButton(b) {
    alert('click');
  }

  onFocusOut($event) {
    this.elOnNo.nativeElement.focus();
  }

When getting an HTML element that has #elementId you'll have to use

@ViewChild('elementId', {static: false}) element: ElementRef

In your case that would be.

@ViewChild('b', {static: false}) elOnNo: ElementRef

Also in your StackBlitz example some methods that are called seem to be missing. 在此处输入图像描述

Here is the documentation for @ViewChild

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM