How to re-render a component manually Angular 5

2020-07-02 09:57发布

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
}

4条回答
老娘就宠你
2楼-- · 2020-07-02 10:08

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'); });
查看更多
\"骚年 ilove
3楼-- · 2020-07-02 10:10

You can use detectChanges() or markForCheck() to tell angular to re-render the component again.

查看更多
你好瞎i
4楼-- · 2020-07-02 10:12

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

查看更多
Ridiculous、
5楼-- · 2020-07-02 10:28

You could trick the router into rendering a fresh copy of current component by temporarily overriding route reuse strategy.. found in some other SO answer :)
in ngOnInit:

this.router.routeReuseStrategy.shouldReuseRoute = () => false;
查看更多
登录 后发表回答