Search code examples
angularangular-router

Access url path inside *ngIf


I need to access the path of my url within a *ngIf. I've tried the following:

import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'my-app',
    providers: [],
    templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {

    constructor(public route: ActivatedRoute) {

    }
}

And in my HTML/Pug:

div(*ngIf='route.firstChild?.url?.value[1]?.path == "somePath"')

It does work when I build it using angular cli but when I try to build it with aot, I get the following error: Property 'value' does not exist on type 'Observable<UrlSegment[]>'

Seems like I'm not allowed to directly access the value of an observable inside *ngIf


Solution

  • It's not that you can't directly access the value of the observable, it's that the value of the observable is undefined when the browser initializes the view. This is in general how Observables work since they are asynchronous in nature.

    Two ways I can think of to solve this:

    1. Use Angular 2's async pipe: https://angular.io/api/common/AsyncPipe. This will allow the view to wait for the next value provided by the observable, and AOT shouldn't complain.
    2. Subscribe to the value of the route either in your constructor or in an ngOnInit lifecycle hook, assign that value to a variable in your component class, and use that component-binded variable in your ngIf statement (make sure your initialize the variable to false if you go this route or AOT may complain that the value is undefined)