将参数发送到模式窗口(Angular 8)

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

我在.ts中有此代码

openFormModal(id: number) {
    console.log(id);
    const modalRef = this.modalService.open(PartidoComponent);
    modalRef.componentInstance.id = id;

    //modalRef.componentInstance.id = id;
    modalRef.result.then((result) => {
      console.log(result);
    }).catch((error) => {
      console.log(error);
    });
  }

以及component.html中的此代码

<button (click)="openFormModal(calendario.fixture_id)">Open Modal</button>

我可以看到来自另一个组件的模式始终是相同的,因为我无法发送相应的id。有人知道如何正确发送参数吗?

angular bootstrap-modal
1个回答
0
投票

创建一个名为child的组件(以显示模式),然后在其HTML中:

<ng-template #childmodal let-modal>
    <div class="modal-header">
        <h4 class="modal-title" id="modal-basic-title">Create New Item</h4>
        <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <form>
        <div class="modal-body">
            <div class="form-group row m-b-15">
                This is a Modal- Id is {{this.itemId}}
            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-outline-primary btn-sm ml-1">Save</button>
            <button type="button" class="btn btn-outline-danger btn-sm" (click)="hideModal()">Close</button>
        </div>
    </form>
</ng-template>

及其打字稿中:

export class ChildComponent implements OnInit {
  public itemId: number;

  private modalRef: NgbModalRef;
  @ViewChild("childmodal", { static: false }) child: any;

  constructor(private modalService: NgbModal) {}

  ngOnInit() {}

  open(id: number) {
    this.itemId = id;
    this.modalRef = this.modalService.open(this.child);
    this.modalRef.result.then(result => {}, reason => {});
  }

  hideModal() {
    this.modalRef.close();
  }
}

现在,在父组件中显示模式:

HTML:

<app-child></app-child>
<button type="button" class="btn btn-sm btn-primary" (click)="this.openModal()">
  Open Modal
</button>

打字稿(在openModal方法中,我们生成一个随机数作为ID发送给模式):

  @ViewChild(ChildComponent, { static: false }) childModal: ChildComponent;

  openModal() {
    const id = Math.floor(Math.random() * 10);
    this.childModal.open(id);
  }

Stackblitz Here

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