My main goal is to accomplish the following :
I currently have a component setup like this:
import { Component, Output, EventEmitter, OnInit } from '@angular/core';
@Component({
selector: 'like',
template: '<p>this is the like component<p>'
})
export class LikeComponent implements OnInit{
title: string = 'Like Component';
@Output() sendTitle = new EventEmitter();
ngOnInit() {
this.sendTitle.emit({title: this.title});
}
}
The intention is to pass the title from this component to its parent:
import { Component, Input } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'panel',
template: `
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">{{title}}</h2>
</div>
<div class="panel-body">
<ng-content (sendTitle) = "receiveTitle($event)"></ng-content>
</div>
</div>
`
})
export class PanelComponent {
title = 'default title';
receiveTitle(arg) {
this.title = arg.title;
console.log(arg);
}
}
This way, I can utilize the PanelComponent
for any content I want in a panel:
<panel>
<like></like>
</panel>
<panel>
<another-component></another-component>
</panel>
<panel>
<example-component></example-component>
</panel>
Every time a Panel
component is displayed, it will attempt to retrieve the title from the event if present.
It seems that using ng-content for this purpose does not work as expected compared to regular parent/child components. Since I am new to Angular 2, I would love to hear your thoughts!
In summary, my aim is for a parent component to access properties of a child component without being specific (hence the use of <ng-content>
).
To clarify, I do not want to achieve this through input
like so:
<panel [title] = "'This is the panel title of the like component'">
<like></like>
</panel>
<panel [title] = "'This is the panel title of the another-component'">
<another-component></another-component>
</panel>