【问题标题】:An error when assigning input bindings when creating components dynamically动态创建组件时分配输入绑定时出错
【发布时间】:2017-07-22 00:31:39
【问题描述】:

我有一个简单的组件:

@Component({
  template: 'I am {{color}} component'
})
export class ColorComponent implements OnInit, OnChanges {
  @Input() color: string;

我正在像这样添加这个组件:

export class AppComponent implements AfterViewInit {
  @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;

  componentRef: ComponentRef<ColorComponent>;

  constructor(private vc: ViewContainerRef, private resolver: ComponentFactoryResolver) {}

  ngAfterViewInit(): void {
    this.createComponent();
  }

  createComponent() {
    this.container.clear();
    const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(ColorComponent);
    this.componentRef: ComponentRef<ColorComponent> = this.container.createComponent(factory);
    this.componentRef.instance.color = 'green';
  }
}

虽然模板渲染正确:

I am green component

我在控制台中收到以下错误:

表达式在检查后发生了变化。以前的值: 'CD_INIT_VALUE'。当前值:“我是绿色组件”。这好像是 视图是在其父级和子级创建之后创建的 脏检查。它是在变更检测钩子中创建的吗?

为什么会出错?

【问题讨论】:

    标签: angular


    【解决方案1】:
    export class ColorComponent implements OnInit, OnChanges {
      constructor(private cdRef:ChangeDetectorRef) {}
      private _color: string;
      @Input() set color(val: string) {
        this._color = val;
        this.cdRef.detectChanges();
      }
    }
    

    如果你不控制动态添加的组件你也可以

    componentRef.instance.color = 'green';
    componentRef.changeDetectorRef.detectChanges();
    

    【讨论】:

    • 谢谢,现在工作正常。您能否详细说明导致问题的原因?或者也许有一些资源可以阅读有关此事的信息?
    • 在变化检测过程中,绑定的属性值发生变化时会抛出错误。我猜原因是您从添加组件的代码中调用代码,但是您的问题不包含有关该信息的信息。通过显式同步更改检测运行,Angular 会更新它为更改检测保存的值副本,并且不再识别更改。
    • 谢谢,我会读到的。 componentRef.instance.color = 'green'; - 我在这里改变价值
    • 我知道,但我不知道这段代码在你的应用程序中的什么位置,以及它是从哪里调用的。
    • 我很确定问题出在ngAfterViewInit() 如果您从(click)="createComponent()" 调用createComponent() 它会正常工作,因为这里Angular 期望更改,但是@ 987654327@被变更检测调用,不喜欢变更检测本身引起变更。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多