在动态创建组件时分配输入绑定时出错

时间:2017-03-02 10:24:37

标签: angular

我有一个简单的组件:

@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'。当前价值:'我是绿色组件'。这好像是   视图已在其父级及其子级之后创建   脏检查。它是否已在变更检测钩子中创建?

为什么会出错?

1 个答案:

答案 0 :(得分:3)

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();