Angular event of receiving 2nd content from a child component

I am creating a page with several dynamic panels, each child panel has the same HTML, so I created a component of the parent panel to wrap them.

The problem is that I want to send an event from a child to the panel, but I cannot find the answer. Here is what I still have:

// 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 common service, but there seems to be an overflow to pass a boolean value from child to parent.

Any ideas?

thank

+4
source share
1 answer

There are several ways.

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

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

DOM, Angular2, ,

'@ContentChildren() `,

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

.

, .

+7

Source: https://habr.com/ru/post/1674071/


All Articles