How to re-render a component manually Angular 5
If i understand you properly you are asking about ChangeDetectionStrategy Angular has two options
enum ChangeDetectionStrategy {
OnPush: 0
Default: 1
}
If you use default it simply will "re-render" you view after each event such a click.
If you are using OnPush, it will re-render if you use observable with | async or you can inject ChangeDetectorRef and "ask" to re-render
constructor(private ref: ChangeDetectorRef) {
setInterval(() => {
this.numberOfTicks++;
// the following is required, otherwise the view will not be updated
this.ref.markForCheck();
}, 1000);
}
But this is true if you are running inside of angular. Sometimes if you are listening to external services and you are running outside of NgZone you need to do ngZone.run
this._ngZone.run(() => { console.log('Do change detection here'); });
If you meant to manipulate the view (add, remove or reattach) then here is an example:
import { Component, ViewContainerRef, AfterViewInit, ViewChild, ViewRef,TemplateRef} from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'host-comp',
template: `
<h1>I am a host component</h1>
<ng-container #vc><ng-container>
<br>
<button (click)="insertChildView()">Insert Child View</button>
<button (click)="removeChildView()">Remove Child View</button>
<button (click)="reloadChildView()">Reload Child View</button>
<ng-template #tpl>
<child-comp><child-comp>
<ng-template>
`
})
export class HostComponent implements AfterViewInit{
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
@ViewChild('tpl', {read: TemplateRef}) tpl: TemplateRef<any>;
childViewRef: ViewRef;
constructor(){}
ngAfterViewInit(){
this.childViewRef = this.tpl.createEmbeddedView(null);
}
insertChildView(){
this.vc.insert(this.childViewRef);
}
removeChildView(){
this.vc.detach();
}
reloadChildView(){
this.removeChildView();
setTimeout(() =>{
this.insertChildView();
}, 3000);
}
}
live example here