【问题标题】:Angular2 ng-bootstrap: Reuse modal template with different dataAngular2 ng-bootstrap:重用具有不同数据的模态模板
【发布时间】:2017-08-09 14:54:13
【问题描述】:

我正在构建一个类似于仪表板的界面,其中包含一组包含可比较数据的实体。这些实体中的每一个都有一个编辑按钮,我想用它来打开一个显示相应数据的模式。

我想重用相同的模态模板,并显示来自单击编辑按钮的实体的数据。我正在使用 Angular2 和 ng-bootstrap,它依赖于 Bootstrap 4。

从ng-bootstrap modal docs 和它随附的plunkr 开始,我能够像这样创建自己的工作模式组件(为布局而简化):

//editmodal.html

<template #content let-c="close" let-d="dismiss">
  //Modal html content
</template>

<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Edit</button>

//dashboard.html

<template ngbModalContainer></template>
<edit-modal></edit-modal>

//editmodal.component.ts

@Component({
  selector: 'edit-modal',
  templateUrl: 'entity/assets/templates/editmodal.html'
})

export class EditModal {
  //exported class logic
}

让我感到奇怪的主要事情是,来自以前的引导程序版本,打开模式的按钮现在显示在模板本身中,并封装了它。这使得附加对它的引用变得困难,因此我可以从类逻辑中找出要显示的内容。如何使用 Angular2 和 ng-bootstrap 实现这种行为?

【问题讨论】:

    标签: angular modal-dialog bootstrap-modal bootstrap-4 ng-bootstrap


    【解决方案1】:

    您可以使用NgbModal 服务从任何地方打开一个包含组件的模式窗口。

    调用this.ngbModalService.open(NgbdModalContent),其中NgbdModalContent 是您要在模态中显示的组件。

    查看组件作为内容:

    https://ng-bootstrap.github.io/#/components/modal

    【讨论】:

    • 我的数据作为 JSON 数组 [{&lt;entity&gt;},{&lt;entity&gt;}] 从服务器获取,我应该将每个对象 cast 到一个组件,然后...?或者那不是要走的路?
    • 没有强制转换。您可以通过设置 NgbdModalContent 的属性来配置模式的内容。像 NgbdModalContent.name = entity.name。该值将出现在 NgbdModalContent 模板的 {{name}} 插值中
    【解决方案2】:

    与 Lev 在他的回答中写的类似,您可以使用 NgbModal.open() 方法并将其传递给组件以填充模式的内容。

    现在,您不只是想要一个组件。您还希望组件从 API 获取数据。您可以通过将NgbModalRef.componentInstance 参数与OnInit 接口结合使用来做到这一点。

    所以解决方案是这样的:

    constructor(
      private modalService: NgbModal
    ) { }
    
    openModal() {
      const modalRef = this.modalService.open(MyComponent)
      modalRef.componentInstance.mycomponent_id = 1;
    }
    

    您的组件如下所示:

    export class PlayerComponent implements OnInit {
      @Input() mycomponent_id;
      myObject: MyObject;
    
      ngOnInit() {
        this.myService.getObject(mycomponent_id)
          .subscribe(value => this.myObject = value);
      }
      ...
    }
    

    所以基本上总结一下。您可以通过将所需的组件作为内容传递给模式来打开模式。然后从组件外部设置 mycomponent_id 值。 此后您的组件将运行ngOnInit() 方法,该方法允许您使用mycomponent_id 值通过您的服务从您的API 中获取正确的数据。

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 2013-03-08
      • 2017-01-12
      • 2017-02-04
      • 1970-01-01
      • 2020-05-12
      • 2023-03-09
      • 2014-08-06
      • 1970-01-01
      相关资源
      最近更新 更多