Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re initialize sub component in angular2?

Tags:

angular

I have a component inside another component, added by tag. At some point, i would like to reinitialize this sub-component, like the first it was invoke. Is there any way to do that?

like image 861
jonyjm Avatar asked Aug 01 '17 16:08

jonyjm


People also ask

How do you reinitialize components?

You can re initialize by making the flag false and true . Can use a ChangeDetectorRef to trigger detection of the toggling without setTimeout e.g. this. flag = false; this. cd.

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

Technically, we do this by feeding the new value in Subject, by just calling next(newValue) , and then it can be sent to all Observers who then need to subscribe it. Taking an example where a message - a string is sent/updated by one component and the other component needs to listen to it and receive/update the same.

How do you Rerender components in angular 13?

Do it manually. 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 .


2 Answers

You can write your own cleanup method. But faster way (but not trully convenient) is to use *ngIf. When value is false, component is completely removed (destroyed) from page. When it is back to true it goes via regular path constructor > ngOnInit, etc. Why it is not convenient?

  • it may look ugly
  • it may require from you to trigger change detection manually

.

reinitChildComponent(): void{     this.childVisible = false;     this.changeDetectorRef.detectChanges();     this.childVisible = true;     this.changeDetectorRef.detectChanges(); } 
like image 120
A. Tim Avatar answered Sep 20 '22 15:09

A. Tim


You can re initialize component using *ngIf.

<mychild *ngIf="flag"></mychild> 

You can re initialize by making the flag false and true.

like image 30
Suresh Kumar Avatar answered Sep 17 '22 15:09

Suresh Kumar