gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:17:00 25 4
gpt4 key购买 nike

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

我看过类似的帖子,但没有一个对我有用,例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com