Though it looks to be a simple one, but it can be achieved using child component and Input, Output variables.
Child Component for displaying the content from the service
@Component({
selector: 'title',
template: `
<div> {{title}}</div>
`,
})
export class TitleComponent implements ngOnChanges{
@Input() title:string="";
@Output() titleChanged:EventEmitter<string>=new EventEmitter<string>();
constructor(){
//service call goes here
}
ngOnChanges(){
console.log(this.val);
this.titleChanged.emit(this.title);
}
}
Parent component will be as
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<title (titleChanged)="changedTitle($event)" [title]="title"></title>
</div>
`,
})
export class App {
name:string;
title:string="some title";
val:string;
constructor() {
this.val="";
}
changedTitle(va){
console.log(va);
}
}
Explanation:
- When service call is made and the title value gets changed.
- On change of the input property the ngOnChanges will be triggered automatically.
- The titleChanged is Output() variable and emits a value when ever ngOnChanges is executed.
- When the titleChanged is triggered, the associated method in the changedTitle() will be executed.
LIVE DEMO
Note: In order to show this is working I have used an text box and assigning it to the div element.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…