angular - 如何调用组件 1 的 html 视图中包含的组件 2 的函数?
问题描述
我有 2 个组件称为principal
和menu
。在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>
解决方案
你可以通过相互绑定来做到这一点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>
推荐阅读
- java - 在使用 mapstruct 映射期间选择正确的源
- javascript - Svelte 迭代对象数组
- javascript - 进行并行下载时,React-Native-fs 下载速度慢
- amazon-web-services - AWS - Terraform - SCP - MalformedPolicyDocumentException
- flutter - 在 iOS 上启动应用程序时出错
- git - 如何忽略 Git 存储库中的文件夹和子文件夹?
- regex - kotlin中字母数字空格和反斜杠的正则表达式
- java - 找不到日期格式
- html - CSS 选择器与非 CSS 选择器无法正常工作
- sql - Windows 10 PRO:DBeaver + ODBC 无连接