Создание динамических вложенных компонентов из ответа json - PullRequest
2 голосов
/ 23 мая 2019

Я пытаюсь создать вложенные динамические компоненты на основе ответа json.

public content={type:'paragraph',depth:1,text:'Root',entityRanges:[{type:'LINK',offset:83,length:16,data:{target:'_self',url:'/index.htm'}}],embbeded:[{type:'text',text:'This is Text component'}]}

Итак, в приведенной выше структуре это тип paragraph, поэтому ParagraphComponent необходимо отобразить первым.

Это как объект массива embbeded, в этом массиве я хотел визуализировать TextComponent.

Таким образом, конечный результат должен быть таким,

<paraComp><p><textComp>This is Text component</textComp></p></paraComp>

Нижечто я пробовал,

Основной компонент

export class AppComponent implements OnInit {
  @ViewChild('container', { read: ViewContainerRef })
  public target: ViewContainerRef;
  public content = { type: 'paragraph', depth: 1, text: 'Root', entityRanges: [{ type: 'LINK', offset: 83, length: 16, data: { target: '_self', url: '/index.htm' } }], embbeded: [{ type: 'text', text: 'This is Text component' }] }

  constructor(private createDynamicComponentService: CreateDynamicComponentService) { }
  ngOnInit() {
    this.createDynamicComponentService.createComponent(this.content, this.target);
  }
}

Основной HTML

<ng-container #container></ng-container>

createDynamicComponentService

export class CreateDynamicComponentService {
  private rootViewContainer: ViewContainerRef;
  private componentFactory: ComponentFactory<any>;
  private componentReference;
  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    @Inject(CONTENT_MAPPINGS) private contentMappings: any
  ) { }

  setRootViewContainerRef(view: ViewContainerRef): void {
    this.rootViewContainer = view;
  }

  createComponent(content: any, container: ViewContainerRef) {
    const type = this.contentMappings[content.type];
    console.log(type);
    this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
    this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);
    this.componentReference.instance.contentOnCreate(content);
  }
}

Ссылка на проект https://stackblitz.com/edit/angular-dynamic-new?file=src/app/app.component.ts

Я взял ссылку из этого https://github.com/sparkles-dev/ng-content-driven-angular/blob/master/src/app/reactive-content/content-host/content-host.component.ts

Основываясь только на этом, я создал свой проект.Но не могу заставить его работать.

Пожалуйста, помогите.

1 Ответ

1 голос
/ 23 мая 2019

Самый простой способ сделать это может выглядеть так:

@Injectable()
export class CreateDynamicComponentService {
  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    @Inject(CONTENT_MAPPINGS) private contentMappings: any
  ) { }

  createComponent(content: any, container: ViewContainerRef) {
    const type = this.contentMappings[content.type];

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
    const componentRef = container.createComponent<any>(componentFactory);

    if (componentRef.instance.contentOnCreate) {
      componentRef.instance.contentOnCreate(content);
    }

    if (!content.embedded) return;

    // render children recursively
    for (const embeddedContent of content.embedded) {
      // in order to render children component must define ViewContainerRef
      if (!componentRef.instance.embeddedContainer) {
        const cmpName = componentRef.instance.constructor.name;
        throw new TypeError(`Trying to render embedded content. 
          ${cmpName} must have @ViewChild() embeddedContainer defined`);
      }

      this.createComponent(embeddedContent, componentRef.instance.embeddedContainer);
    }
  }

}

Для визуализации дочерних компонентов компонент должен определить контейнер, в котором будут отображаться дочерние компоненты, например:

paragraph.component.html

<p>
  <ng-container #embeddedContainer></ng-container>
</p>

paragraph.component.ts

export class ParagraphComponent implements OnInit {
  @ViewChild('embeddedContainer', { read: ViewContainerRef }) embeddedContainer: ViewContainerRef;

Разветвленный стек-блиц

...