在Angular 2中,如何让组件与嵌套对话框组件交互
How to have component interact with nested dialog component in Angular 2?
我有一个通用组件。该组件有N个按钮,其中N可以由父组件设置。父组件可以有这个通用组件的多个实例。当在通用组件上单击按钮时,我需要通知父组件该按钮已被按下,并以某种方式确定哪个按钮已被按下。然后,我需要让父组件能够调用嵌套组件上的一些函数。下面是我想要做的一个非常粗略的例子:
@Component({
selector: 'parent-component',
...
})
export class ParentComponent{
public OnGenericComponentButtonPress(someId){
if (someId === "foo"){
genericComponentInstance.closeComponent();
}else{
doOtherThing();
}
}
}
@Component({
selector: 'generic-component',
...
})
export class GenericComponent{
public closeComponent(){}
}
我需要一些像这样来回交流的方法。假设父组件可以有多个GenericComponent实例,这是可能的吗?
你需要2个沟通形式:
- 子节点到父节点
- 父级到子级
子元素到父元素
从子组件到父组件的通信可以通过在子组件上添加eventemitter并订阅父组件上的事件来完成。通过调用EventEmitter
emit
来调用父节点。子组件代码:
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'my-child',
template: '<h2>{{myText}}</h2><button (click)="onClick()">do something</button>'
})
export class ChildComponent {
private myText = "Child Component";
@Output() clicked: EventEmitter<any> = new EventEmitter();
public onClick() {
this.clicked.emit();
}
}
父组件代码:
import { Component} from '@angular/core';
import { ChildComponent } from "./child.component";
@Component({
selector: 'my-app',
template: `<h1>Parent component</h1>
<my-child (clicked)="doSomething()"></my-child>`,
directives: [ChildComponent]
})
export class AppComponent {
public doSomething() {
do something...
}
}
父级到子级
要调用子组件,我们首先需要获得对该组件的引用,如果我们有多个相同类型的组件,则通过使用ViewChildren来完成。
父组件代码:
import { Component, ViewChildren, QueryList} from '@angular/core';
import { ChildComponent } from "./child.component";
@Component({
selector: 'my-app',
template: `<h1>Parent component</h1>
<my-child></my-child>`,
directives: [ChildComponent]
})
export class AppComponent {
@ViewChildren(ChildComponent) children:QueryList<ChildComponent>;
public callChild(){
this.children.toArray()[0].doSomething();
}
}
示例
注意:组件之间还有其他通信方式,例如使用公共服务。
相关文章:
- 在嵌套组件中使用 react 组件时模块中断
- 在 React 中嵌套组件,props 不会传递给子组件
- 如何使用嵌套的 React 组件从“链接页面”的顶部开始
- ReactJs - 列表组件中的嵌套列表组件
- 嵌套的React/Rerelay组件未接收道具
- DefaultRouter组件中的嵌套路由
- 反应:在嵌套组件上冒泡点击事件
- 如何访问Vue.js中深度嵌套的子组件中的数据
- 根据location.hash传递的数据重新呈现ReactJS嵌套的子组件
- 如何使用React和Redux在嵌套容器中测试组件
- Angular 1.5 嵌套组件绑定父值
- 在 knockoutjs 中嵌套组件
- 您如何处理 Angular2 中嵌套组件的依赖关系
- 获取嵌套在聚合物纸张对话框中的自定义Web组件内内容的客户端高度
- 在嵌套的边框容器内容窗格小组件中未检测到区域属性
- 如何处理 React 嵌套组件循环依赖?(使用 es6 类)
- AngularJS通过嵌套组件向上传播更改
- Aura.js闪电组件:从超级/父组件触发嵌套/子组件的方法
- 如何在 RivetsJS 中处理递归嵌套组件
- 了解嵌套组件绑定在 KnockoutJS 上的工作原理