@Viewchild Angular 5, 6 - ElementRef

1

I am referencing a control using ElementRef and for this I use the following:

 @ViewChild('btnGuardarDatosGenerales') btnGuardarDatosGenerales: ElementRef;

I need the reference to be able to reach your click () event, with javascript I can achieve doing it:

let buttonDG: any = document.getElementsByName('btnGuardarDG')[0];
buttonDG.click();

but when doing it with ElementRef I do not get it:

this.btnGuardarDatosGenerales.nativeElement.click();

... I could do it with javascript but it's not the idea. Any suggestions, in which I can be wrong?

Thank you.

    
asked by configbug 08.08.2018 в 21:37
source

2 answers

0

The code that I will put below would simulate a click on the element you need. Obviously you would have to run it from the (click) of the parent button that you mentioned or from somewhere else. If you are really in the parent component this should work.

@ViewChild('btnGuardarDatosGenerales') btnGuardarDatosGenerales: ElementRef;

simularClick() {
    let boton: HTMLElement = this.btnGuardarDatosGenerales.nativeElement as HTMLElement;
    boton.click();
}

I hope you serve, greetings.

    
answered by 08.08.2018 в 21:59
0

Make sure you are using the button reference after AfterViewInit . Also use the identifier btnGuardarDatosGenerales has to be in the mode button:

<button #btnGuardarDatosGenerales ...> ...</botton>

That way the @ViewChild('btnGuardarDatosGenerales') will have access to it.

I leave you a Functional Stackblitz .

    
answered by 08.08.2018 в 22:26