如何使用angular2在身体上附加内容

时间:2018-08-09 12:51:26

标签: angular typescript angular2-template angular2-directives

我正在尝试在my-app内而不是在我的身体上显示弹出窗口,那么如何使用anular 2显示在身体上的弹出窗口我尝试了但没有工作,这有可能吗? https://stackblitz.com/edit/angular-t4yerr?file=src/app/app.component.ts

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
</dependency>

1 个答案:

答案 0 :(得分:1)

您的方法是错误的。您所做的只是复制HTML条目,但这还不够,因为您失去了从Angular到此HTML元素的连接。

该问题有多种解决方案,不过您可以查看例如at this article下面的代码是从文章中复制的

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

@Injectable()
export class DomService {

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

  appendComponentToBody(component: any) {
    // 1. Create a component reference from the component 
    const componentRef = this.componentFactoryResolver
      .resolveComponentFactory(component)
      .create(this.injector);

    // 2. Attach component to the appRef so that it's inside the ng component tree
    this.appRef.attachView(componentRef.hostView);

    // 3. Get DOM element from component
    const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement;

    // 4. Append DOM element to the body
    document.body.appendChild(domElem);

    // 5. Wait some time and remove it from the component tree and from the DOM
    setTimeout(() => {
        this.appRef.detachView(componentRef.hostView);
        componentRef.destroy();
    }, 3000);
  }
}

这样,您不仅可以重定位HTML对象。您可以将Angular绑定到此HTML元素。

另一种方法是查看ready modal library,它可以为您完成所有工作(包括将组件托管在体内)。此外,您可以检查their implementation的组件到身体的重定位