Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-render a component manually Angular 5

Tags:

Is there a way I can re render a component manually, say when a user clicks a button??

I've seen similar posts but none of these worked for me for example here

For example,

renderComponent() {    // force component re-render } 
like image 887
Smokey Dawson Avatar asked May 17 '18 03:05

Smokey Dawson


People also ask

How do you're-render an element in angular?

The very basic approach works by wrapping the element you want to rerender inside a ng-template element that gets rendered into a ng-container . On rerender you can just clear the content of the ng-container and create a new component from the ng-element .

How do you refresh a component from another component in angular 6?

To refresh, or better to say update another component from a different component, we can use the concept of Observables and Subject (which is a kind of Observable). This concept has an added benefit when data are to be received from APIs for CRUD operations.

How do I not render a component?

1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.


1 Answers

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

like image 172
sugarme Avatar answered Nov 19 '22 09:11

sugarme