DEV Community

Cover image for Ionic 4 angular router + NavigationExtras interface
Micha
Micha

Posted on

Ionic 4 angular router + NavigationExtras interface

Example to pass data between components in Ionic 4/angular:
using NavigationExtras interface

Especially when passing data in dialogs there is often no parent/child-relation ship. So you can't pass data in angular way (parent -> child). In Ionic 4/angular you have this feature to pass data comfortable within the router by the interface NavigationExtras.

page1 pass data to page2

page1.ts

import {NavigationExtras, Router} from '@angular/router';
import {Component} from '@angular/core';

@Component({
    selector: 'page1',
    templateUrl: 'page1.html',
    styleUrls: ['page1.scss'],
})
export class Page1 {
    public data: string;
    public value: string;

    constructor(private router: Router) {
    }
    // route page2 and set params in NavigationExtras
    public routePage2() {
        const navigationExtras: NavigationExtras = {
            state: {
                data: this.data,
                value: this.value
            }
        };
        this.router.navigate(['/page2'], navigationExtras);
    }
}

Enter fullscreen mode Exit fullscreen mode

page2.ts

import {ActivatedRoute, Router} from '@angular/router';
import {Component} from '@angular/core';
@Component({
    selector: 'page2',
    templateUrl: 'page2.html',
    styleUrls: ['page2.scss'],
})
export class Page2 {
    public data: string;
    public value: string;

    constructor(private route: ActivatedRoute, private router: Router) {
        this.route.queryParams.subscribe(params => {
            if (this.router.getCurrentNavigation().extras.state) {
                this.data = this.router.getCurrentNavigation().extras.state.data;
                this.value = this.router.getCurrentNavigation().extras.state.value;
            }
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

refer to: point 4
https://ngrefs.com/router/navigationextras
https://angular.io/api/router/NavigationExtras

Top comments (0)