在ngFor中调用modal时动态调用模态并传递参数?

时间:2018-06-01 04:23:13

标签: angular ng-bootstrap

我想实现类似的目标,但Angular 6 https://embed.plnkr.co/plunk/PskWpI

我正在做这样的事情(在我看来,这不是一个好习惯,因为modal html会多次生成):

组件模板:

 <div *ngFor="let element of elements">
    <div *ngFor="let data of element">
         //******modal html will be generated several times)******
         <app-form-modal [data]="data"></app-form-modal>
     </div>
 </div>

//This is what's inside <app-form-modal [data]="data"></app-form-modal>
 <ng-template #content let-c="close" let-d="dismiss">
    <div class="modal-header">
        <h4 class="modal-title">Modal title</h4>
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <p>RENDER THE DATA HERE</p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
    </div>
</ng-template>
<button class="btn btn-lg btn-outline-primary" (click)="open(content, data)">Launch demo modal</button>

组件类:

import { Component, OnInit, Input } from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-form-modal',
  templateUrl: './form-modal.component.html',
  styleUrls: ['./form-modal.component.css']
})
export class FormModalComponent implements OnInit {
    @Input() d: any[];
    closeResult: string;

    constructor(private modalService: NgbModal) {}

    open(content, data) {
      console.log(data);
        this.modalService.open(content).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        });
    }    
}

我的意见的最佳方法是创建一个调用模态的button,并在其中动态生成data,而不是在{{1}内多次生成modal }。但是我如何实现这个目标呢?

ngFor

0 个答案:

没有答案