Angular 2 - 为什么动态组件的绑定被破坏?

时间:2017-04-27 09:32:32

标签: javascript jquery angular typescript

我动态生成一个组件

var componentFactory = this.componentFactoryResolver.resolveComponentFactory(TransportOrderComponent);

let dynamicComponent = this.container.createComponent(componentFactory);

动态组件中属性的绑定不起作用。 (例如,ngIf,按钮单击,......)

组件html:

<button (click)="show = !show">toggle: {{show ? 'hide' : 'show'}}</button>
<br>
<div *ngIf="show"> Text to show</div>

Component TypeScript:

...
export class TransportOrderComponent {
  show: boolean = true;
}

作为静态组件,一切正常。如果我添加dyn组件并单击静态组件按钮,动态组件的内容会更改一次

enter image description here

Hier是plunkr

1 个答案:

答案 0 :(得分:2)

那是因为你在角度区域之外运行代码。

这应该对你有用

constructor(private zone: NgZone, ...) {}

addTransportOrderComponent(jqContainer: any) {
  this.zone.run(() => {
     let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TransportOrderComponent);
     let dynamicComponent = this.container.createComponent(componentFactory);
  })
}

<强> Modified Plunker