【问题标题】:Angular 2 ng-content receive event from child componentAngular 2 ng-content 从子组件接收事件
【发布时间】:2017-04-05 09:49:17
【问题描述】:

我正在构建一个包含多个动态面板的页面,每个子面板都有相同的 HTML,因此我创建了一个父面板组件来包装每个面板。

问题是我想将一个事件从孩子发送到面板,但我似乎找不到答案。到目前为止,这是我所拥有的:

// Panel Panel Component
@Component({
    selector: 'panel',
    template: `
    <div (emittedEvent)="func($event)">
        <ng-content></ng-content>
    </div>
    `
})
export class PanelComponent {

    constructor() {}

    func(event) {
    // Do stuff with the event
    }
}
// Child Panel Component (one of many)
@Component({
selector: 'child-panel-one',
template: `
    // Template stuff
    <button (click)="emitEvent()">Click</button>
`
})
export class ChildPanelOne {
emittedValue: Boolean = false;

@Output() emittedEvent = new EventEmitter();

constructor() {}

private emitEvent() {
    this.emittedValue = true;

    this.emittedEvent.emit(this.emittedValue)
}
}
//
// Main Parent Template
<panel>
    <child-panel-one></child-panel-one>
</panel>

我可以创建一个共享服务,但将布尔值从子级传递给父级似乎有点过头了。

有什么想法吗?

谢谢

【问题讨论】:

    标签: angular angular2-ngcontent


    【解决方案1】:

    有几种方法

    <panel #p>
        <child-panel-one (emittedEvent)="p.func($event)"></child-panel-one>
    </panel>
    

    但这需要&lt;panel&gt; 的用户设置事件绑定

    或者您可以像in Angular2 how to know when ANY form input field lost focus 中所示的 DOM 事件

    或者你可以使用 ´@ContentChildren()` 然后强制订阅

    @ContentChildren(ChildPanelOne) childPanels:QueryList<ChildPanelOne>
    
    ngAfterContentInit() {
      this.childPanels.toArray().forEach(cp => cp.emittedValue.subscribe(() => ...));
    }
    

    但这要求所有子面板都是预定义的类型。

    您还可以使用带有可观察对象的共享服务,子组件注入并使用它向父组件发出事件。

    【讨论】:

    • 感谢您的回答和链接。该服务似乎是最好的方法 - 这样面板组件不需要如上所述定义的所有子面板。我创建了一个非常简单的服务,范围仅限于面板及其子项
    • 对于其他有类似问题的人,这个 Plunkr 演示了共享的 EmitterService plnkr.co/edit/Kt7jpEwzKC8ljvKGLbKt?p=preview
    • 感谢您的反馈。很高兴听到您能找到适合您的解决方案。我也会使用服务。
    • 您还可以让所有内容子组件从具有通用输出(例如 onChange)的基本组件继承,并使用 在您的组件中订阅它在其模板中。
    【解决方案2】:

    从内容子项捕获事件的另一种方法是获取父组件的 ref 并定义

    constructor(app:AppComponent){ //<-- get the ref of the parent component
        app['clic'] = this.clic; //<-- declare function and bind our function 
        this.name = 'myself';
    }
    
    clic(){
        alert('clicked');
    }
    
    ngOnDestroy() {
        delete this.app['clic']; // <-- get rid of the function from parent component, when we are done
    }
    

    WORKING DEMO (CHECK THIS ALSO)

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      相关资源
      最近更新 更多