【发布时间】: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