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 }
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With