将参数发送到模态 window (Angular 8)

Send an parameter to a modal window (Angular 8)

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

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

typescript(在 openModal 方法中我们生成一个随机数作为 Id 发送到模态):

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

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

Stackblitz Here

感谢您的回答。

对我来说,解决方案如下: 此代码是正确的:

modalRef.componentInstance.id = id;

然后我在 ngOnInit 中写了一个 console.log 并且值显示正确然后我将执行 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);
       });
     });
   }

希望对你有所帮助,如果有人知道比这个更好的解决方案,请