【问题标题】:Angular 2 - Why is the binding of dynamic components broken?Angular 2 - 为什么动态组件的绑定被破坏?
【发布时间】:2017-09-25 00:32:43
【问题描述】:

我动态生成一个组件

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>

组件 TypeScript:

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

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

这是plunkr

【问题讨论】:

    标签: javascript jquery angular typescript


    【解决方案1】:

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

    这应该适合你

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

    Modified Plunker

    【讨论】:

      猜你喜欢
      • 2015-08-21
      • 2023-03-04
      • 1970-01-01
      • 2019-10-13
      • 2019-02-16
      • 2011-04-19
      • 1970-01-01
      • 2018-02-02
      相关资源
      最近更新 更多