Angular 2 Router - named router-outlet navigation from code - angular2-routing

Using #angular/router": "3.4.7".
Proposed solution here doesn't work anymore.
/**
The ProductComponent depending on the url displays one of two info
components rendered in a named outlet called 'productOutlet'.
*/
#Component({
selector: 'product',
template:
` <router-outlet></router-outlet>
<router-outlet name="productOutlet"></router-outlet>
`
})
export class ProductComponent{
}
#NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{
path: 'product',
component: ProductComponent,
children: [
{
path: '',
component: ProductOverviewComponent,
outlet: 'productOutlet'},
{
path: 'details',
component: ProductDetailsComponent,
outlet: 'productOutlet' }
]
}
]
)],
declarations: [
ProductComponent,
ProductHeaderComponent,
ProductOverviewComponent,
ProductDetailsComponent
exports: [
ProductComponent,
ProductHeaderComponent,
ProductOverviewComponent,
ProductDetailsComponent
]
})
export class ProductModule {
}
Manual navigation works as expected
http://localhost:5000/app/build/#/product-module/product (correctly displays overview component in named outlet)
http://localhost:5000/app/build/#/product-module/product/(productOutlet:details)
(correctly displays details component in named outlet)
THE PROBLEM
Cannot figure out the correct way to perform programatical navigation:
this.router.navigateByUrl('/(productOutlet:details)');
this.router.navigate(['', { outlets: { productOutlet: 'details' } }]);
Following errors occur:
Error: Cannot match any routes. URL Segment: 'details'.

You can navigate programatically like this
this.router.navigate([{ outlets: { outletName: ['navigatingPath'] } }], { skipLocationChange: true });
Note: skipLocationChange is use to hide the url from the address bar.
Refer the official document : https://angular.io/guide/router

You can try relative navigation as
this.router.navigate(['new'],{relativeTo:this.route})
For this you will have to inject current router snapshot and Activated route in component as
import { Router,ActivatedRoute } from "#angular/router";
constructor(private router:Router,private route:ActivatedRoute ){}

Related

How can i create two layouts and use them?

i want to use another layout just for the admin
{
path: '/admin',
name: 'admin',
meta: { layout: 'LayoutAdmin' },
component: Admin,
},
in my component Admin i got this
import { useRoute } from 'vue-router'
const route = useRoute()
console.log('router', route.meta) // i got { layout: 'LayoutAdmin' }
how can i use the layoutAdmin? only for this page?

Storybook with Angular Couldn't find story matching 'story-title--task-name'

I try to work with Storybook in my Angular project, and I run into a misterious error message, and I have no clue what's happening here.
This is my tag.component.stories.ts file:
import { CommonModule } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { RouterModule } from '#angular/router';
import { Meta, moduleMetadata, Story } from '#storybook/angular';
import { AppRoutingModule } from 'src/app/app-routing.module';
import { TagComponent } from './tag.component';
export default {
title: 'Attached Tags',
component: TagComponent,
decorators: [
moduleMetadata({
declarations: [TagComponent],
imports: [BrowserModule, CommonModule, RouterModule, AppRoutingModule]
})
]
} as Meta;
const Template: Story = (args) => ({
props: {
...args
}
});
export const GreenPost = Template.bind({});
GreenPost.args = {
tag: {
id: 1,
name: 'Test tag',
color: '#bada55',
type: 'Post'
}
};
I get this error message:
Couldn't find story matching 'attached-tags--green-post'.
- Are you sure a story with that id exists?
- Please check your stories field of your main.js config.
- Also check the browser console and terminal for error messages.
So, I'm pretty sure after reading the documentation's "Simple component" section I don't have any idea how or where should I need to define any id for stories.
Here is my .storybook/main.js:
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions"
],
"framework": "#storybook/angular",
"core": {
"builder": "webpack5"
}
}
This is the factory default I think.
Also checked the browsers console, and nothing else, just the visible message twice.
Any idea how can I solve this issue?

What am I missing so I can use the router on Nativescript?

I am attempting to build my first ever app using nativescript. I am going through the docs but not sure what I'm missing so I can't fix it.
I have the following structure:
- app
-- app-routing.module.ts
-- app.component.html
-- app.component.ts
-- app.css
-- app.module.ts
- home
-- home.component.css
-- home.component.html
-- home.component.ts
- restaurant
-- restaurant.component.css
-- restaurant.component.html
-- restaurant.component.ts
The thing is, I am trying to make it so that when someone taps on an element in the home.component.html:
<Image class="h3 m-5" col="0" row="0" src="~/images/beet-logo.jpg" (tap)="visitRestaurant()" height="87" width="80"></Image>
They are redirected to the restaurant.component.html page.
I defined the tap event as shown up there and then I have on my home.component.ts the following:
import { Router } from "#angular/router";
import { Component, OnInit } from "#angular/core";
#Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html",
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private router: Router) {
}
visitRestaurant() {
this.router.navigate(["/restaurant"]);
}
ngOnInit(): void {
}
}
When I click it, it fails though with the error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'restaurant'
I thought about adding the route here and also into app-routing.module.ts but whenever I try I get cannot find name: RestaurantComponent. So I assume I need to export the component somewhere but not sure where or how.
Can you guys help me?
This is my app-routing-module.ts in case it's useful:
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./home/home.module#HomeModule" }
];
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }
Here's my restaurant.component.ts code:
import { Router } from "#angular/router";
import { Component, OnInit } from "#angular/core";
#Component({
selector: "Restaurant",
moduleId: module.id,
templateUrl: "./restaurant.component.html",
styleUrls: ['./restaurant.component.css']
})
export class RestaurantComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit(): void {
}
}
You need to add a route for /restaurant. For example, you might do:
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./home/home.module#HomeModule" },
{ path: "restaurant", component: RestaurantComponent }
];
Additionally, you'll want to make sure your export/import statements appear appropriately.
Within restaurant.component.ts:
#Component({ ... })
export class RestaurantComponent { ... }
Within app-routing.module.ts:
import { RestaurantComponent } from ' ... ';

got this error, Error: Cannot match any routes

import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { LmfinComponent } from '../app/lmfin/lmfin.component';
import { MfinComponent } from './mfin/mfin.component';
import { GenFunctionProvider } from './gen-function.module';
import {DetailpembayaranComponent } from './detailpembayaran/detailpembayaran.component';
const appRoutes:Routes = [ //removed export
{ //removed square bracket
path: '',
redirectTo: '/mfin',
pathMatch: 'full'
},{
path: 'list',
component: LmfinComponent
},{
path: 'mfin/:id',
component: MfinComponent
},{
path: 'detailpembayaran',
component: DetailpembayaranComponent
}
];
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(appRoutes, {useHash:true})
],
declarations: []
})
export class AppRoutingModule { }
i'm still new at routing, when i try to makes routing, i got this error
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
anyone can help me please?
You default path to redirect /mfin
You no path with /mfin you have URL /mfin/:id. This is not match with /mfin
So need to add route URL of /mfin.
Try this, As far as I understood you are missing some codes in index.html. Check whether you have below code in your index.html head section. If not add it and see.
<base href="/">
Also ensure your server has configured for HTML5 pushState like explained in Angular 2.0 router not working on reloading the browser
I hope this will resolve your problem. If you have any doubts or suggestion let me know.

want to navigate from one page to another page using child module

Child Module
​const routes: Routes = [
{ path: '', component: ProcComponent,
children:[{
path: '/LoadProcResultsdata/:procResults', component: ProcResultsComponent,
}]
}
];
App.Module.ts
​const routes: Routes = [
{ path: 'app', component: AppComponent },
{ path: 'home', component: HomeComponent },
{ path: 'treeview', component: TreeViewComponent },
{path:'Proc', loadChildren:'app/proc/Proc.Module#ProcModule'}
];
My code
this.router.navigate(['/LoadProcResultsdata/'],{ queryParams: { procResults:this.results } });
But I am getting following error.
core.umd.js:3064 EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'LoadProcResultsdata'
Error: Cannot match any routes. URL Segment: 'LoadProcResultsdata'
There are couple of issues,
remove front / from the path,
children:[{
path: '/LoadProcResultsdata/:procResults', component: ProcResultsComponent,
}]
Also you need to use route params rather query params, so you can use below,
this.router.navigate(['/LoadProcResultsdata', this.results]);
I am assuming this.results is some ID, so the resulting url becomes
/LoadProcResultsdata/<id>
Read more abour route parmeters here.
Update:
you can do that but not with route params, just with queryParams, remove :procResults, and use similar code like below,
let extra: any = ['abc','xyz'];
let navigationExtras: NavigationExtras = {
queryParams:extra
};
this.router.navigate(['/LoadProcResultsdata'],navigationExtras);
and in the navigted component subscribe to ActivatedRoute queryParams,
constructor( private route: ActivatedRoute) {
route.queryParams.subscribe(params => {
console.log(params);
})
}
Check this Plunker!!
another Plunker with Lazy loaded module.

Resources