elver
elver

Reputation: 111

Access a method of one component from another

I am in Angular and I need to invoke a method of one component from another.

Having this component:

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

@Component({
  selector: 'app-popover',
  templateUrl: './popover.component.html',
  styleUrls: ['./popover.component.scss']
})
export class PopoverComponent implements OnInit {

  constructor() {}
  @Input() texto:string;


  toggleWithGreeting(popover, texto: string) {
    if (popover.isOpen()) {
      popover.close();
    } else {
      popover.open({texto});
    }
  }

  ngOnInit(): void {}

}

I need to reach the toggleWithGreeting method from the parent component, I have this:

send(){
    this.renderer.selectRootElement(this.popName.nativeElement).toggleWithGreeting("","");
}

But it does not work, I am not able to access the method, the html if you can help is this:

 <app-popover #popName [texto]="'Esto va a ser el mensaje de error'" ></app-popover>

Upvotes: 2

Views: 80

Answers (1)

Oussail
Oussail

Reputation: 2288

You should use ViewChild in the parent component :

import { ViewChild } from '@angular/core';

@ViewChild('popName', { static: true }) popName: PopoverComponent;

Then you can call your function like this :

this.popName.toggleWithGreeting("", "");

Upvotes: 7

Related Questions