alphapilgrim
alphapilgrim

Reputation: 3975

Programmatically click button in child component form

I'm trying to click a button on a form inside a child component. I've tried using ViewChild & ViewChildren also, referencing the template ref as ElementRef. It all returns the values and not the native elements. stackblitz-demo

import {
  Component,
  ViewChild,
  AfterViewInit,
  ElementRef
} from '@angular/core';
import {
  HelloComponent
} from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  @ViewChild('test') form: ElementRef;
  name = 'Angular';

  ngAfterViewInit() {
    console.log(this.form);
  }
}



import {
  Component,
  Input
} from '@angular/core';

@Component({
  selector: 'hello',
  template: `
  Child Component
    <form class="login-as-user" [action]="formUrl" method="post" target="_blank">
      <input id="login-as-user" type="submit" value="reference this button">
    </form>
`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  @Input() name: string;
}

Upvotes: 5

Views: 12442

Answers (2)

Xinan
Xinan

Reputation: 3162

All you need is this: @ViewChild('test', {read: ElementRef}) form: ElementRef;

For more information please read the following article:

Angular @ViewChild: How to read multiple tokens

Upvotes: 4

abdullahkady
abdullahkady

Reputation: 1071

You can add a function in the child component that in fact clicks programmatically on it's own button by using ViewChild of the desired button, then accessing nativeElement.click().

Then trigger that function from the parent component with another ViewChild for the child component

Child :

  • Template : <input id="login-as-user #buttomToBeClicked>
  • TS: @ViewChild('buttonToBeClicked') buttonToBeClicked: ElementRef;

Then add the click function:

clickButton(){
  this.buttonToBeClicked.nativeElement.click();
}

Parent :

  • Template : <hello #child></hello>
  • TS: @ViewChild('child') child;

Then call the click function in your parent component like this:

this.child.clickButton();

Edit:

You can just do this.child.buttonToBeClicked.nativeElement.click(); as a shortcut, but communication through an extra method gives you more flexibility to add any checks in your child component

Upvotes: 6

Related Questions