将参数发送到模态窗口(角度8)

时间:2019-10-29 01:32:55

标签: angular rest api bootstrap-modal ng-bootstrap

我在.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。有人知道如何正确发送参数吗?

2 个答案:

答案 0 :(得分:3)

创建一个名为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

答案 1 :(得分:0)

谢谢您的回答。

对我来说,解决方法如下: 这段代码是正确的:

modalRef.componentInstance.id = id;

然后,我在console.log中写了一个ngOnInit,并正确显示了值,然后我以这种方式将执行API查询的代码移到了该部分:

ngOnInit () {
     console.log (this.id);
     this.activatedRoute.params.subscribe ((params) => {
       this.lpefService.getPartidos (this.id)
       .subscribe ((data: any) => {
         this.partidos = data.api.fixtures;
         console.log (this.parts);
       });
     });
   }

modal

console.log

我希望它能对您有所帮助,如果有人知道比该解决方案更好的解决方案,请