如何将@Input()参数传递给使用DynamicComponentLoader创建的角度2组件

Jul*_*lfs 11 angular

DynamicContentLoader文档没有解释我如何正确加载子组件的输入.假设我有一个孩子喜欢:

@Component({
  selector: 'child-component',
  template: '<input type="text" [(ngModel)]="thing.Name" />'
})
class ChildComponent {
  @Input() thing : any;
}
Run Code Online (Sandbox Code Playgroud)

和父母一样:

@Component({
  selector: 'my-app',
  template: 'Parent (<div #child></div>)'
})
class MyApp {
  thing : any;
  constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
    dcl.loadIntoLocation(ChildComponent, elementRef, 'child');
  }
}
Run Code Online (Sandbox Code Playgroud)

我应该如何thing进入子组件,以便两个组件可以绑定同一个数据.

我试着这样做:

@Component({
  selector: 'my-app',
  template: 'Parent (<div #child></div>)'
})
class MyApp {
  thing : any;
  constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
    dcl.loadIntoLocation(ChildComponent, elementRef, 'child').then(ref => {
        ref.instance.thing = this.thing;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

它有点工作,但它们没有像你期望的那样同步.

基本上我试图通过在角度1中使用ng-include来实现同样的事情,其中​​子项是动态确定的组件并与其父项共享模型.

提前致谢 ...

Thi*_*ier 5

我为你的问题做了一些测试,我无法重现它.

这是我的子组件的内容:

@Component({
  selector: 'child-component',
  template: `
    <div>
      Child component - <input type="text" [(ngModel)]="thing.name" />
    </div>
  `
})
export class ChildComponent {
  @Input() thing : any;

  constructor() {
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是父组件的内容:

@Component({
  selector: 'my-dyn-parent',
  template: `
    <div>
      Parent component - <input type="text" [(ngModel)]="thing.name" /> (<br/>
        <div #child></div>
      <br/>)
    </div>
  `
})
export class ParentComponent {
  thing : any;
  constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
    this.thing = { name: 'test name' };
    dcl.loadIntoLocation(ChildComponent, elementRef, 'child')
                     .then((compRef:ComponentRef) => {
      compRef.instance.thing = this.thing;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我在同一个元素上绑定了两个输入:一个在父组件中,一个在子组件中.当我更新一个输入中的值时,另一个值将在另一个输入中更新.

因此,两个组件共享同一个实例并可以更新它.也许我在你的用例中遗漏了一些东西,所以请随时告诉我!

希望它对你有帮助,蒂埃里

  • 如果`thing`是一个对象或一个数组,这个解决方案很有效,因为父和子都得到对同一个对象的引用.但是,如果`thing`是基本类型(String,number,boolean),它就不起作用 - parent和child各自得到它们自己的原语.[Plunker](http://plnkr.co/edit/MuvEyCLOzNX3J28ZI3UY?p=preview).Eric的EventEmitter解决方案似乎是一种更通用的解决方案(它适用于引用类型和原始类型). (2认同)