有没有办法可以手动重新渲染组件,比如当用户单击按钮时?
我看过类似的帖子,但这些帖子都不适合我here https://stackoverflow.com/questions/35105374/how-to-force-a-components-re-rendering-in-angular-2
例如,
renderComponent() {
// force component re-render
}
如果您打算操作视图(添加、删除或重新附加),那么这里是一个示例:
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);
}
}
活生生的例子在这里 https://stackblitz.com/edit/ng-embedded-view
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)