Reload child component when variables on parent component changes. Angular2
Use @Input
to pass your data to child components and then use ngOnChanges
(https://angular.io/api/core/OnChanges) to see if that @Input
changed on the fly.
update of @Vladimir Tolstikov's answer
Create a Child Component that use ngOnChanges
.
ChildComponent.ts::
import { Component, OnChanges, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'child',
templateUrl: 'child.component.html',
})
export class ChildComponent implements OnChanges {
@Input() child_id;
constructor(private route: ActivatedRoute) { }
ngOnChanges() {
// create header using child_id
console.log(this.child_id);
}
}
now use it in MasterComponent's template and pass data to ChildComponent like:
<child [child_id]="child_id"></child>
On Angular to update a component including its template, there is a straight forward solution to this, having an @Input
property on your ChildComponent and add to your @Component
decorator changeDetection: ChangeDetectionStrategy.OnPush
as follows:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent{
@Input() data: MyData;
}
This will do all the work of check if Input data have changed and re-render the component