tamtakoe
tamtakoe

Reputation: 237

How to transfer callback method to the ng-bootstrap modal (Angular 2+)?

I want to do primitive thing - transfer method save to my modal. I do it this way:

@Component({
  selector: 'ngbd-modal-content',
  template: `
    <div class="modal-header">
      <h4 class="modal-title">Hi there!</h4>
      <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
         <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <input [(ngModel)]="name"/>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-success" (click)="save()">Save</button>
      <button type="button" class="btn btn-outline-dark" (click)="activeModal.close('Close click')">Close</button>
    </div>`
})
export class NgbdModalContent {
  @Input() name;
  @Output() action; //Actually I can use @Input or nothing

  constructor(public activeModal: NgbActiveModal) {}

  save() {
    this.action(this.name)
  }
}

@Component({
  selector: 'ngbd-modal-component',
  templateUrl: 'src/modal-component.html',
  providers: [HttpClient]
})
export class NgbdModalComponent {
  constructor(private modalService: NgbModal, private http: HttpClient) {}

  open() {
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.name = 'World';
    modalRef.componentInstance.action = this.save.bind(this); //bind!!!
  }

  save(name) {
    console.log(name)

    this.http.get('https://api.github.com/users?page=1&per_page=10').subscribe(data => {
      console.log(data)
    })
  }
}

It works but it doesn't look like the best way. I have to bind this for save method. It doesn't clear. Maybe there is better way?

http://plnkr.co/edit/lJH2KHCnZBtHYDtSbraU?p=preview

Upvotes: 1

Views: 4137

Answers (1)

St&#233;phane GRILLON
St&#233;phane GRILLON

Reputation: 11862

1) Remove:

@Output() action; //Actually I can use @Input or nothing

2) Remove:

modalRef.componentInstance.action = this.save.bind(this); //bind!!!

3) Save function close this modal with a result (name for you but you can use a form object)

save() {
    this.activeModal.close(name);
}

4) Add a callback on caller:

// close action is result
// dismiss action is reason
open() {
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.name = 'World';
    modalRef.result.then((result) => {
                   this.save(result);
                 }, (reason) => {
                   console.log('Dismissed action: ' + reason);
                 });
} 

save(user) {
    console.log('save action: ' + user);
}

Upvotes: 5

Related Questions