【问题标题】:How to update a value in the dynamically added child component in Angular 9如何更新Angular 9中动态添加的子组件中的值
【发布时间】:2021-07-16 04:08:36
【问题描述】:

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

@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变量的值发生变化时如何更新子组件视图?

【问题讨论】:

  • 如果您在子组件中使用@Input(),是否需要在父组件中使用@ViewChild?只需传递变量并在父组件中更改其上下文,或使用 ngOnChanges()

标签: angular typescript angular9 angular-dynamic-components


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    视图相关的操作只能在调用 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';
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-26
      • 2020-08-13
      • 2021-02-17
      • 2020-10-17
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多