angularangular2-ngcontent

Angular 2 ng-content receive event from child component


I am building a page with several dynamic panels, each child panel has the same HTML so I have created a parent panel component to wrap each one.

The problem is I want to send an event from the child to the panel but I cant seem to find an answer. Here's what I have so far:

// 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>

I could create a shared service but it seems an overkill for passing a boolean value from child to parent.

Any ideas?

Thanks


Solution

  • There are several ways

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

    but this requires the user of <panel> to set up the event binding

    or you could a DOM event like shown in in Angular2 how to know when ANY form input field lost focus

    or you could use ´@ContentChildren()` and then subscribe imperatively

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

    but that requires all child panels to be of predefined types.

    You could also use a shared service with an observable that child components inject and use to emit events to the parent component.