有没有一种方法可以手动重新渲染组件,比如当用户点击按钮时??
我看过类似的帖子,但没有一个对我有用,例如 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);
}
}
关于angular - 如何手动重新渲染组件 Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383003/