动态组件 - createComponent - OnChanges

Jor*_*vis 6 angular

我正在通过该createComponent方法创建一个动态组件,并且无法让我的child组件更新从via方法input传递到其中的值,但是当我更新子组件中的值时,它并没有更新它的引用。parentcomponent.instance.prop = somevalueparent

父组件:

import {
  Component,
  ViewChild,
  ViewContainerRef,
  ComponentFactoryResolver,
  AfterContentInit
} from '@angular/core';

import { ChildComponent } from '../child/child.component';

@Component({
  selector: 'parent-component',
  template: `
    <div>
      <input type="text" (keyup)="name = $event.target.value">
      <span>{{ name }}</span>
    </div>
    <ng-container #container></ng-container>
  `,
  styles: []
})
export class ParentComponent implements AfterContentInit {
  @ViewChild('container', { read: ViewContainerRef}) container: ViewContainerRef;
  private _name = 'John Doe';
  get name() {
    return this._name;
  }
  set name(name: string) {
    this._name = name;
  }
  constructor(private resolver: ComponentFactoryResolver) { }

  ngAfterContentInit() {
    let factory = this.resolver.resolveComponentFactory(ChildComponent);
    let component = this.container.createComponent(factory);
    component.instance.name = this.name;
  }
}
Run Code Online (Sandbox Code Playgroud)

子组件:

import {
  Component,
  OnInit,
  Input,
  OnChanges,
  SimpleChanges
} from '@angular/core';

@Component({
  selector: 'child-component',
  template: `
    <div>
      {{ name }}
    </div>
  `,
  styles: []
})
export class ChildComponent implements OnChanges {
  _name: string;
  get name() {
    return this._name;
  }
  set name(name: string) {
    this._name = name;
  }
  constructor() { }
  ngOnChanges(changes: SimpleChanges) {
    console.log('onchanges ', changes);
    this._name = changes.name.currentValue;
  }
}
Run Code Online (Sandbox Code Playgroud)

问题:如何获取child通过createComponent()方法创建的动态组件,以便在组件中的值发生变化时更新其值parent

Aby*_*lay 7

您可以在父组件中执行此操作。这里是 stackblitz 中的例子。

template: `
<div>
  <input type="text" (keyup)="onKeyUp($event)">
  <span>{{ name }}</span>
</div>
<ng-container #container></ng-container>
`,

childComponent: ChildComponent;

ngAfterContentInit() {
  let factory = this.resolver.resolveComponentFactory(ChildComponent);
  let component = this.container.createComponent(factory);
  this.childComponent = component.instance;
  this.childComponent.name = this.name;
}

onKeyUp($event) {
  const changes = {
    name: new SimpleChange(this.name, $event.target.value, false)
  }

  this.name = $event.target.value;
  this.childComponent.ngOnChanges(changes);
}
Run Code Online (Sandbox Code Playgroud)