ngx bootstrap - 在模板中嵌套组件

问题描述 投票:1回答:1

我们的应用程序中有一个标准模态。

<ng-template [ngIf]="true" #editDataModal>
   <div class="modal-header">
     <h5 class="modal-title">Edit Modal</h5>
     <button type="button" class="close" aria-label="Close" (click)="onCancelClicked()">
       <span aria-hidden="true">&times;</span>
     </button>
   </div>
  <div class="modal-body" #editDataModalBody>CUSTOM COMPONENT GOES HERE</div>
 </ng-template>

我们希望能够传递自定义组件作为我们的身体。在ngx bootstrap中有没有办法做到这一点?

看来该模式出现在主要内容之外,因此我们无法使用ViewChild找到它。

我们使用模态服务来调用它。像这样: -

  constructor(
    private modalService: BsModalService
  ) { }

ngOnInit() {
   this.modalConfig = {
      ignoreBackdropClick: true
    };

   this.ModalRef = this.modalService.show(this.editModal, this.modalConfig);
}
angular6 ngx-bootstrap ngx-bootstrap-modal
1个回答
0
投票

模态组件可以获取并发布ViewContainerRef。例如,它可以使用BehaviorSubject。父组件可以创建自定义组件,并在发布viewContainerRef时将其添加到模式。我只是这样做而不只是一个getter,因为ViewChild在afterViewInit之前无效,所以你需要一种方法来处理它。

// EditModalComponent
export class EditModalComponent implements AfterViewInit {
  @ViewChild("editDataModalBody", {read: ViewContainerRef}) vc: ViewContainerRef;

  public bodyRefSubject: BehaviorSubject<ViewContainerRef> = new BehaviorSubject<ViewContainerRef>(null);

  constructor(
    public bsModalRef: BsModalRef,
    public vcRef: ViewContainerRef
  ) {}

  ngAfterViewInit() {
    this.bodyRefSubject.next(this.vc);
  }

  onCancelClicked() {
    console.log('cancel clicked');
    this.bsModalRef.hide()
  }
}

在父组件中:

// Parent Component
export class AppComponent {
  bsModalRef: BsModalRef;
  bodyContainerRef: ViewContainerRef;
  customComponentFactory: ComponentFactory<CustomComponent>;
  modalConfig: ModalOptions;

  constructor(
    private modalService: BsModalService,
    private resolver: ComponentFactoryResolver
  ) {
    this.customComponentFactory = resolver.resolveComponentFactory(CustomComponent);
  }

  openModalWithComponent() {
    this.modalConfig = {
      ignoreBackdropClick: true,
    }
    this.bsModalRef = this.modalService.show(EditModalComponent, this.modalConfig);
    this.bsModalRef.content.bodyRefSubject.subscribe((ref) => {
      this.bodyContainerRef = ref;
      if (this.bodyContainerRef) {
        this.bodyContainerRef.createComponent(this.customComponentFactory);
      }
    })
  }
}

不使用ViewChild的另一种方法是在div上放置一个指令而不是#editDataModalBody,该指令可以注入ViewContainerRef并使用服务或类似方法发布它。

© www.soinside.com 2019 - 2024. All rights reserved.