Umair Umair - 29 days ago 20
AngularJS Question

angular2 child route, no component

I'm trying to make an 'edit' url for my entity. So, for example

/my-site/entity/1
and
/my-site/entity/1/edit
. The
edit
part is just used to toggle a state of the main/parent entity url.

In angular 1, with the ui-router I could do something along the lines of

.state("home.entity.edit", {
url: "/edit",
reloadOnSearch: false
})


I.e. this would be child state of
home.entity
. It would have no view or controller as the parent state would handle it. Also on toggle to this state, nothing would actually happen in terms of redirect/controller execution.

Is it actually possible to do this with the component router in angular2?

Answer

For the moment, I've implemented it as follows

{
    path: 'view/:id',
    component: NotesViewComponent,
    children: [
        {
            path: '',
            component: null
        },
        {
            path: 'edit',
            canActivate: [EditModeActivator],
            component: null
        }
    ],
    data: {
        editMode: false
    }
}

where

@Injectable()
class EditModeActivator implements CanActivate {
    constructor() { }

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (next.url[0].path === "edit") {
            let data: any = next.parent.data;
            data.editMode = true;
        }

        return true
    } 
}

It is a hack yes, but will do for now!