0

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
        })
    }
}
1
  • 3
    It is generally a bad practice to use jQuery with Angular framework. Instead of using Bootstrap+jQuery, I would suggest you try ng-bootstrap or ngx-bootstrap which are built for Angular and do not depend on jQuery. Commented Sep 16, 2018 at 18:20

2 Answers 2

1

Use this keyword like that in Jquery.

ngAfterViewInit() {
var self = this;
    $('#mymodal').on('hidden.bs.modal', function (e) {
        self.router.navigate(['/']);
    })
}
Sign up to request clarification or add additional context in comments.

Comments

1

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(['/']);
  })
}

3 Comments

Tried that as well, gives me "this.router is undefined"
Please update your question with the latest code that you've tried.
Did you try with the above syntax (arrow function)? The above code will only work with arrow function, since that function will not have its own this. If you are going with the traditional anonymous function "function (e) { " you need to assign this to a custom var before the callback (as in suggestion below)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.