首页 > 解决方案 > 如何调用组件 1 的 html 视图中包含的组件 2 的函数?

问题描述

我有 2 个组件称为principalmenu。在menu组件中,我有一个 json 对象和一个 html 代码,当我单击一个元素时,我希望在其中调用principal组件中包含的函数。我希望当我单击此功能时,所选对象显示在principal组件中。我知道这可以在单个组件中完成,但我正在尝试创建我遇到的实际问题的场景。谢谢你。

应用程序组件

<menu></menu>
<principal></principal>

菜单组件

import { Component, Input } from '@angular/core';
@Component({
selector: 'menu',
template: `Select a animal: <br> <button *ngFor="let item of aAnimals" (click)="getAnimal(item);" style="display:block;">{{item.animal}}</button>`,
styles: [`h1 { font-family: Lato; }`]
})
export class MenuComponent  {
 aAnimals=
 [
  {"animal":"cat"},
  {"animal":"dog"},
  {"animal":"horse"}
 ]
 constructor(){

}

主成分

import { Component, Input } from '@angular/core';
@Component({
  selector: 'principal',
  template: `<h1>animal selected: {{animal}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class PrincipalComponent  {
  animal:any;
  constructor(){

  }
  public getAnimal(item) {
    alert(item)
    this.animal=item.animal;
  }

}

这是我的代码:

https://stackblitz.com/edit/angular-paamqn

这回答了我的问题。最后一个疑问。在我的真实代码中,我是否<menu>principal组件中调用了如何使它工作?它会改变什么?我不能再使用#principal。

代替

<principal #principal></principal>

principal直接是组件的代码html

<!-- html of principal.component.html -->
<menu (callPrincipalMethod)="principal.getAnimal($event)"></menu>
<h1>animal selected: {{animal}}</h1>

标签: angular

解决方案


你可以通过相互绑定来做到这一点EventEmitter

<menu (callPrincipalMethod)="principal.getAnimal($event)"></menu>
<principal #principal></principal>

菜单组件:

import { Component, Input,  Output, EventEmitter } from '@angular/core';
@Component({
selector: 'menu',
template: `Select a animal: <br> <button *ngFor="let item of aAnimals" (click)="getAnimal(item);" style="display:block;">{{item.animal}}</button>`,
styles: [`h1 { font-family: Lato; }`]
})
export class MenuComponent  {
 @Output()
 callPrincipalMethod = new EventEmitter()

 aAnimals=
 [
  {"animal":"cat"},
  {"animal":"dog"},
  {"animal":"horse"}
 ]
 constructor(){}

 getAnimal(item) {
  this.callPrincipalMethod.emit(item)
 }
}

堆栈闪电战: https ://stackblitz.com/edit/angular-ko2d58

更新

如果menu组件在principal组件内部,只需省略主体principal.getAnimal($event)

<!-- html of principal.component.html -->
<menu (callPrincipalMethod)="getAnimal($event)"></menu>
<h1>animal selected: {{animal}}</h1>

推荐阅读