First, the generation routing file
Conventionally, there is a separate module to configure the routing of this module class name is AppRoutingModule, app-routing.module.ts file located in the src / app in.
Using the CLI to generate it.
ng generate module app-routing --flat --module=app
Then if the success of the next generation to see src / app directory.
Next, we see the generated files:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ imports: [ CommonModule ], declarations: [] }) export class AppRoutingModule { }
Usually you do not declare component routing module, so you can delete and delete references.@NgModule.declarations
CommonModule
Second, export RouterModule
AppRoutingModule at the moment is this:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; @NgModule({ exports: [ RouterModule ] }) export class AppRoutingModule {}
Third, add a route defined
Angular typical route (the Route) has two properties:
1, path: one for the string of the URL in the browser address bar matches.
2, component: When navigating this route, the route which component should be created.
If you want to say when the URL is http: // localhost: 4200 / when homePage, first of all you want to import HomePageComponent; to refer to it in the Route.
as follows:
import { NgModule } from '@angular/core'; import {RouterModule, Routes} from "@angular/router"; import {HomePageComponent} from "../home-page/home-page.component"; const routes: Routes = [ { path: 'homePage', component: HomePageComponent } ]; @NgModule({ exports: [RouterModule] }) export class AppRoutingModule { }
RouterModule.forRoot()
Initialize the router, and it starts to monitor the browser's address changes. (Added to the array)@NgModule.imports
imports: [ RouterModule.forRoot(routes) ],
note:
Are there introduced AppRoutingModule view app.module.ts file.
import { AppRoutingModule } from './app-routing/app-routing.module';
imports: [ AppRoutingModule ],
Fourth, export add routes
Open the template AppComponent of the <router-outlet> added to it, <router-outlet> tells the router to be trying to show the route where.
<router-outlet></router-outlet> // src/app/app.component.html
Fifth, run the project
View project page, pay attention to whether your CLI command line is still running:
serve the
Address bar, enter http: // localhost: 4200, this time you will see the address bar displays the title of the project, but not the content HomePageComponent display.
Sixth, add a default route
Method One: When the project started, the address bar of the browser points to the root path of the site. It does not match to any existing routes, the router will not navigate to any place.
Let the application automatically navigate to the dashboard, add the following route to AppRoutingModule.routes array.
{ path: '', redirectTo: '/homePage', pathMatch: 'full' },
Now access the project again, you will find the address bar by default will be redirected to an empty path routing '/ homePage'; and home is also loaded with HomePageComponent.
Method Two:
{ path: '**', component:DashboardComponent}
It means that when a route URL equals '', will be to load DashboardComponent components; so you run your service port number: localhost: 4200 will be the first load components;
**
Path is a wildcard , he said that apart from the above several path, any path will be loaded DashboardComponent components, remember to write in the final routing configuration.
Seven, add routing link (routerLink)
It should not only allow users to paste the URL into the address bar route. They should also can click on a link to navigate.
Add an <nav>
element, and where to put a link <a> element, when clicked, will trigger a navigation to DetailsComponent of.
<div> home-page works! <nav> <a routerLink="/details">点击查看详情</a> </nav> </div>
DetailsComponent also need to be introduced into the AppRoutingModule.
Click for details on this link. Address bar into a / details, and the page to jump to the details page.
Eight, add details view (HTML parameter passing)
Now suppose we have to show on a list of articles, then we need to click on each pass view the article details; if we want to navigate to the id of the article 11 of the detail view, similar to http: // localhost: URL 4200 / heroes / 11's .
First open AppRoutingModule and import HeroesComponent.
import {HeroesComponent} from "./heroes/heroes.component";
Then add a route to the parametric AppRoutingModule.routes
array, it should match the path to Article detail view.
{ path: 'heroes/:id', component: HeroesComponent }
path
The colon ( :
) represents :id
a placeholder, which represents a particular hero id
.
At the moment, the route is ready to go.
Then, we need to modify the list of articles Jump links in HTML pages, so that they can navigate to the article details page parameterized route.
<NAV> <a routerLink="/heroes/{{id}}"> Click to view article details </a> <-! array format mass participation -> <A [routerLink] = "[ '/ Heroes', num] "> click here for articles details </a> </ NAV>
Now we refresh the page, click view article details, you find that the address bar has been changed to http: // localhost: 4200 / heroes / 11, page display has to jump to the article details page module.
Nine, js page Jump (parameter passing)
When you HeroesComponent introduced in AppRoutingModule, and add a route to the parametric AppRoutingModule.routes
array.
We now need to pass parameters by js Jump to HeroesComponent (several commonly used method):
1, first add the following import statement:
import { Router } from '@angular/router';//引入
It is then ActivatedRoute
injected into the constructor, to save their values in the private variables:
constructor (private router: Router) {} // constructor injected into
2, delivery route parameters
Single parameter passing
Navigate () method supports routerLink instructions and parameter types the same, so their effect is the same:
this.router.navigate(['heroes', id]);
or:
this.router.navigate(['heroes']);
Multi-parameter transfer
this.router.navigate(['heroDetail'], {queryParams: {productId: '1',title: 'moon'}
3, we note that there is a: navigateByUrl (), this is called an absolute route;
this.router.navigateByUrl('home');
Difference: navigateByUrl () and Navigate () is a point of difference: navigateByUrl not determined in accordance with the routing address parameter.
Ten, routing parameters extracted from the id
1, first add the following import statement:
import { ActivatedRoute } from '@angular/router';
It is then ActivatedRoute
injected into the constructor, to save their values in the private variables:
constructor( private route: ActivatedRoute, ) {}
ActivatedRoute
Holds to this HeroDetailComponent
routing information instance. This component interested in routing parameters extracted from the URL. Which id
parameter is to be displayed heroic id
.
2, obtaining routing parameters
method one:
this.route.queryParams.subscribe(queryParams => { let productId = queryParams.productId; let title = queryParams.title; });
Method Two:
code show as below:
public params; //公有变量 ngOnInit() { this.getData(); } getData() { this.route.params.subscribe( params => { this.params = params; console.log(this.params); } ); }
Such an object is obtained, direct access to id on it.
Method three:
code show as below:
ngOnInit(): void { this.getData(); } getData(): void { const id = +this.route.snapshot.paramMap.get('id'); console.log(id); }
XI, the same route back
1, first add the following import statement:
import { Location } from '@angular/common';
Then the Location
service is injected into the constructor, to save their values to private variables in:
constructor( private location: Location ) {}
location
Angular is a service for dealing with the browser. Later , you'll use it to navigate back to the previous view.
2, click Back Page:
By clicking on the browser's Back button to return to the previous page also buy your entry.
Back button to add a base assembly template and bind it to the component goBack () method.
<button (click)="goBack()">go back</button>
Add in a component class goBack()
method, use of injection of Location
the service a step back in history stack browser later.
goBack(): void { this.location.back(); }