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

标签 angular typescript

有没有一种方法可以手动重新渲染组件,比如当用户点击按钮时??

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

例如,

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

最佳答案

如果您打算操作 View (添加、删除或重新附加),那么这里是一个示例:

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

关于angular - 如何手动重新渲染组件 Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383003/

相关文章:

javascript - 在 mailto : string not working as expected 中使用 es6 模板文字

typescript,import * as,没有带括号属性访问器的索引签名

angular - 在 Angular 中更改页面时表格不显示数据

angular - 使用 ngFor Angular 创建复选框列表

javascript - 为什么我们不能在数组函数参数中省略数组破坏中的括号?

html - 显示真棒字体 - Angular 2

angular - 在 IIS 中托管 Angular 4 应用程序后出现 HTTP 错误 500.19 内部服务器错误

google-app-engine - 如何在页面刷新时使 Angular 2 路由与 App Engine 一起工作?

Angular 2根据掩码验证输入

css - 如何更改mat-select的背景颜色并将选择框的边缘更改为圆形样式?