如何手动重新渲染组件Angular 5

时间:2018-05-17 03:42:30

标签: angular typescript

有没有办法可以手动渲染组件,比如当用户点击按钮时?

我看过类似的帖子,但其中没有一个对我有用,例如here

例如,

renderComponent() {
   // force component re-render
}

5 个答案:

答案 0 :(得分:4)

如果我理解你,你会问 ChangeDetectionStrategy Angular有两个options

enum ChangeDetectionStrategy {
  OnPush: 0
  Default: 1
}

如果你使用默认值,它只会“重新渲染”你在每次事件之后查看,例如点击。

如果您正在使用OnPush,如果您使用带有|的observable,它将重新渲染async或你可以注入ChangeDetectorRef和“ask”重新渲染

constructor(private ref: ChangeDetectorRef) {
    setInterval(() => {
      this.numberOfTicks++;
      // the following is required, otherwise the view will not be updated
      this.ref.markForCheck();
    }, 1000);
  }

但如果你在角度内跑,这是真的。有时,如果您正在收听外部服务而且您在NgZone之外运行,则需要执行ngZone.run

this._ngZone.run(() => { console.log('Do change detection here'); });

答案 1 :(得分:2)

如果你打算操纵视图(添加,删除或重新附加),那么这是一个例子:

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

答案 2 :(得分:2)

您可以使用detectChanges()markForCheck()告诉angular再次重新渲染组件。

答案 3 :(得分:1)

您可以通过暂时覆盖路由重用策略来欺骗路由器渲染当前组件的新副本。.在其他一些SO回答中找到:)
在ngOnInit中:

this.router.routeReuseStrategy.shouldReuseRoute = () => false;

答案 4 :(得分:0)

我尝试了该线程中的答案,但我必须进行修改才能使其正常运行。让我分享我的工作代码。

.html-----------------

<button (click)="addChild()">ADD</button>
<button (click)="removeChild()">REMOVE</button>

<ng-container #vc></ng-container>
<ng-template #tpl>
   <child-component id ="child-modal"></child-component>
</ng-template>

.ts---------------------
import { Component, ViewChild, ViewContainerRef, TemplateRef, ViewRef } from '@angular/core';

export class ParentComponent{

@ViewChild('vc', { read: ViewContainerRef }) vc: ViewContainerRef;
@ViewChild('tpl', { read: TemplateRef }) tpl: TemplateRef<any>;

addChild(){
let view = this.tpl.createEmbeddedView(null);
this.vc.insert(view);
}

removeChild(){
 this.vc.clear();
}

This page很有帮助。确保在let view = this.tpl.createEmbeddedView(null);

中添加addchild()