0

I want to open a modal window with item's details using ng-bootstrap after other component has been clicked, but I have a problem with transferring the component argument.

I've tried suggestion from other topic here to use @ViewChild('content') content; but it doesn't work, all I get is an empty modal.

app.component.ts:

import {Component, OnInit, ViewChild} from '@angular/core';
import {ModalComponent} from './modal/modal.component';

export class AppComponent implements OnInit {

  @ViewChild('content') content;
  @ViewChild(ModalComponent) modalCmp;
  modalBeer;

  showModal(item) {
    this.modalBeer = item;
    this.modalCmp.open(this.content);
  }

}

app.component.html:

<main>
  <div class="container">
    <div class="row align-items-stretch">
      <app-grid-item
        *ngFor="let item of beers"
        [beer]="item"
        (click)="showModal(item)"
        class="col-sm-4">
      </app-grid-item>
    </div>
  </div>
  <app-modal [beer]="modalBeer"></app-modal>
</main>

modal.component.ts:

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

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss']
})
export class ModalComponent {

  closeResult: string;

  @Input() beer;

  constructor(private modalService: NgbModal) {
  }

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

modal.component.html:

<ng-template #content let-c="close" let-d="dismiss">
[...]
</ng-template>
Dandy
  • 929
  • 2
  • 14
  • 23
  • 1
    You case is the same as [this other one](https://stackoverflow.com/a/48100223/1009922). Since the `content` template is defined in `ModalComponent`, you should declare `@ViewChild('content')` in that class and define your function as just `open()` (in which you would call `this.modalService.open(this.content)`). – ConnorsFan Jan 06 '18 at 20:30
  • Possible duplicate of [trigger NgbModal without a button but via function call](https://stackoverflow.com/questions/48099246/trigger-ngbmodal-without-a-button-but-via-function-call) – ConnorsFan Jan 06 '18 at 20:33
  • 1
    @ConnorsFan thank you! I've finally understood, I was using `@ViewChild('content') content;` in the wrong component. Thank you! – Dandy Jan 06 '18 at 21:16

0 Answers0