简体   繁体   中英

Use injected dependency in jQuery event listener in angular

I'm using Bootstrap 4 modals in Angular 6 and I want to redirect the user to another route once the modal is closed. However, I'm getting a scoping issue when the modal is closed telling me that my injected router is undefined.

My code:

import { Component, OnInit } from '@angular/core';

declare var $: any


@Component({
    selector: 'app-modal',
    templateUrl: './modal.component.html',
    styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
    constructor(
        public router: Router
    ) {}

    ngOnInit() {}

    ngAfterViewInit() {
        $('#mymodal').on('hidden.bs.modal', function (e) {
            router.navigate(['/']) //tells me that router is undefined
        })
    }
}

Use this to have access to the router as an injected dependency and arrow function syntax( (e) => {} ) to rescope it to the correct scope. Like this:

ngAfterViewInit() {
  $('#mymodal').on('hidden.bs.modal', (e) => {
    this.router.navigate(['/']);
  })
}

Use this keyword like that in Jquery .

ngAfterViewInit() {
var self = this;
    $('#mymodal').on('hidden.bs.modal', function (e) {
        self.router.navigate(['/']);
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM