繁体   English   中英

如何更新 Angular 中动态添加的子组件中的值 9

[英]How to update a value in the dynamically added child component in Angular 9

我有一个动态添加子组件的父组件

@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';
  }

}

而子组件如下

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`
})
export class HelloComponent {
  @Input() name: string;
}

当我单击按钮(ref.instance.name='Bird')更改名称的值时,它不会使用新的名称值更新子组件视图。 我也尝试了 ref.changeDetectorRef.detectChanges() 但即使这样也不会更新子组件视图。 我在网上阅读文章说 changeDetectorRef.detectChanges() 在主机视图上而不是在组件本身上运行。
当 name 变量的值发生变化时,如何更新子组件视图?

更新输入后调用ref.changeDetectorRef.detectChanges(); 触发变更检测

ngOnInit() {
    const factory = this.fr.resolveComponentFactory(HelloComponent);
    const ref = this.vcr.createComponent(factory);
    ref.instance.name = 'World';
    ref.changeDetectorRef.detectChanges();  
}

视图相关的操作只能在调用 ngAfterViewInit 内部或之后进行。 我尝试了您的示例并将您的代码移至 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM