将子组件添加到父组件,并将父组件添加到文档

时间:2019-04-18 10:15:00

标签: angular angular6 angular7 angular-components

在Angular 7模态服务中,我正在创建模态Stackblitz

模态只是添加到文档中的DIV,如下所示:

const modal = document.createElement('div');
modal.classList.add('modal');
modal.appendChild(this.element);

document.body.appendChild(this.modal);

modal内容(this.element)是动态创建的组件。

我希望modal也是动态添加的组件:

  1. 从ModalComponent创建模态(我认为与2类似);
  2. 创建元素组件(DONE);
  3. 将元素组件添加为模态组件的子代;
  4. 将模式组件添加到文档中。

有人可以帮我解决(3)和(4)吗?不知道该怎么做。

模式

export class Modal {
  protected modal: any = null;
  close() {
    this.modal.close();
  }
}

ModalService

import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector, ComponentRef, ReflectiveInjector } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class ModalService {

  private component: ComponentRef<any>;
  private element: any;
  private stage: any;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private application: ApplicationRef, private injector: Injector) { }

  open(component: any, data: any): void {

    if(this.element) 
      return;

    const injector: Injector = ReflectiveInjector.resolveAndCreate([{ provide: 'modal', useValue: data }]);

    this.component = this.componentFactoryResolver.resolveComponentFactory(component).create(injector);

    this.component.instance.modal = this;

    this.application.attachView(this.component.hostView);

    this.element = (this.component.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

    const modal = document.createElement('div');
    modal.classList.add('modal');
    modal.appendChild(this.element);

    document.body.appendChild(this.modal);

  }

  close(): void {

    this.application.detachView(this.component.hostView);
    this.stage.parentNode.removeChild(this.stage);
    this.component.destroy();
    this.element = null;

  }

}

1 个答案:

答案 0 :(得分:2)

首先,您需要动态创建该内部组件,然后在extension UIFont { public static func CreateWithStyle(name: String, size: CGFloat, styles: [UIFontDescriptor.SymbolicTraits]) -> UIFont { let fontDescriptor = UIFontDescriptor(name: name, size: size) var fontAtrAry = fontDescriptor.symbolicTraits if styles.count > 0 { for style in styles { fontAtrAry.update(with: style) } } return UIFont(descriptor: fontDescriptor.withSymbolicTraits(fontAtrAry)!, size: size) } } 方法中使用projectableNodes参数将其投影到动态创建的ComponentFactory.create中。

该ModalComponent应该在其模板中具有ng-content标签:

ModalComponent

modal.service.ts

<div class="stage">
  <div class="modal">
    <ng-content></ng-content>
  </div>
</div>

Forked Stackblitz