網站搜尋

html - 從一個組件訪問另一個組件的方法


我正在使用 Angular,我需要從一個元件調用另一個元件的方法。

擁有這個組件:

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 {}

}

我需要從父組件訪問 toggleWithGreeting 方法,我有這個:

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

但是它不起作用,我無法訪問該方法,如果你能幫忙的話,HTML是這個:

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

答案#1

你應該在父組件中使用 ViewChild:

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

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

然後你可以這樣調用你的函數:

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