Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

javascript - Dynamic component with ng-content attribute?

I would create a modal with this structure:

<div class="modal">

 <div class="modal-body">
  <ng-content select="[body]"></ng-content>
 </div>
 
 <div class="modal-footer">
  <ng-content select="[footer]"></ng-content>
 </div>
 
</div>

And create a content to pass with injection

<div body>
  this is body
</div>
<div footer>
  this is footer
</div>

I tried to do it with a modalService in which I use ComponentFactoryResolver but it doesn't work...it positions content in the first ng-content available without attribute reference.

import {
  ApplicationRef,
  ComponentFactoryResolver,
  ComponentRef,
  Injectable,
  Injector
 } from "@angular/core";
import { ModalComponent } from "./modal/modal.component";

@Injectable()
 export class ModalService {
   dialogComponentRef: ComponentRef<ModalComponent>;

   open(content: any) {
    const contentComponentFactory = this.cfResolver.resolveComponentFactory(content);
    const modalComponentFactory = this.cfResolver.resolveComponentFactory(ModalComponent);

    const contentComponent = contentComponentFactory.create(this.injector);
    const modalComponent = modalComponentFactory.create(this.injector, [[contentComponent.location.nativeElement]]);

    this.dialogComponentRef = modalComponent;

    document.body.appendChild(modalComponent.location.nativeElement);

    this.appRef.attachView(contentComponent.hostView);
    this.appRef.attachView(modalComponent.hostView);
  }

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

this is a stackblitz example I made:

https://stackblitz.com/edit/angular-ivy-jtha5i

Is possible to do it in some way?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...