[英]How to update a value in the dynamically added child component in Angular 9
I have a parent component that dynamically adds child components我有一个动态添加子组件的父组件
@Component({
selector: 'app-parent',
template: `<p>Parent:</p><ng-container #dynamic></ng-container>`
})
export class ParentComponent implements OnInit {
@ViewChild('dynamic', { read: ViewContainerRef }) vcr: ViewContainerRef;
constructor(private fr: ComponentFactoryResolver) {
}
ngOnInit() {
const factory = this.fr.resolveComponentFactory(HelloComponent);
const ref = this.vcr.createComponent(factory);
ref.instance.name = 'World';
}
}
And the child component is as follows而子组件如下
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`
})
export class HelloComponent {
@Input() name: string;
}
When I change the value of name on click of a button (ref.instance.name='Bird') it doesn't update the child component view with the new value of name.当我单击按钮(ref.instance.name='Bird')更改名称的值时,它不会使用新的名称值更新子组件视图。 I tried ref.changeDetectorRef.detectChanges() as well but even that doesn't update the child component view.
我也尝试了 ref.changeDetectorRef.detectChanges() 但即使这样也不会更新子组件视图。 I read articles online which said that changeDetectorRef.detectChanges() runs on the host view not on the component itself.
我在网上阅读文章说 changeDetectorRef.detectChanges() 在主机视图上而不是在组件本身上运行。
How do I update the child component view when the value of name variable changes?当 name 变量的值发生变化时,如何更新子组件视图?
After you update inputs call ref.changeDetectorRef.detectChanges();
更新输入后调用
ref.changeDetectorRef.detectChanges();
to trigger change detection触发变更检测
ngOnInit() {
const factory = this.fr.resolveComponentFactory(HelloComponent);
const ref = this.vcr.createComponent(factory);
ref.instance.name = 'World';
ref.changeDetectorRef.detectChanges();
}
View related manipulation should be done only inside or after ngAfterViewInit is called.视图相关的操作只能在调用 ngAfterViewInit 内部或之后进行。 I tried your sample and moved your code to ngAfterViewInit method and it started working.
我尝试了您的示例并将您的代码移至 ngAfterViewInit 方法并开始工作。
@Component({
selector: 'app-root',
template: `<p>Parent:</p><ng-container #dynamic></ng-container>`,
styleUrls: ['./app.component.less']
})
export class AppComponent implements AfterViewInit {
title = 'dynamic-child';
@ViewChild('dynamic', { read: ViewContainerRef }) vcr: ViewContainerRef;
constructor(private fr: ComponentFactoryResolver) {
}
ngAfterViewInit(): void {
const factory = this.fr.resolveComponentFactory(HelloComponent);
const ref = this.vcr.createComponent(factory);
ref.instance.name = 'World';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.