Отправить параметр в модальное окно (Angular 8) - PullRequest
0 голосов
/ 29 октября 2019

У меня есть этот код в .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 ]

2 голосов
/ 29 октября 2019

Создайте компонент с именем 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();
  }
}

Now, в родительском компонентедля отображения модальных:

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

0 голосов
/ 30 октября 2019

Спасибо за ваши ответы.

Для меня решение было следующим: Этот код был верным:

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

Надеюсь, это поможет вам, если кто-нибудь знает лучшее решение, чем то, пожалуйста

...