Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of routing and form in Angular

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the example analysis of routing and form in Angular, which is very detailed and has certain reference value. Friends who are interested must read it!

Introduction to the routing of Angular

In a single page application, you need to switch back and forth between defined different views (components) without going to the server to get new pages. To navigate from one view to another, you need to use Router in Angular.

Scenarios where routing redirection is required:

If there are two jump links on the page, we hope that when we click on these links, we can jump to the item list page and the personal center page respectively. We can first create two components, GoodsListComponent and PersonalCenterComponent. The specific process is as follows:

Route creation

1. Create a new file app-routing.module.ts, and put the view configuration to be redirected into it.

Import {NgModule} from'@ angular/core';// introduces routing modules RouterModule and Routesimport {Routes, RouterModule} from'@ angular/router'; / / introduces components import {GoodsListComponent} from'. / goods-list/goods-list.component';import {PersonalCenterComponent} from'. / personal-center/personal-center.component' that need to be displayed under different URL. / / configured route array const routes: Routes = [{path: 'goodsList', / / define the route name component: GoodsListComponent, / / specify the component displayed}, {path:' personalCenter', / / define the route name component: PersonalCenterComponent, / / specify the component displayed}] The @ NgModule ({/ / forRoot () method creates a NgModule that contains all instructions, the given route, and the Router service itself. Imports: [RouterModule.forRoot (routes)], exports: [RouterModule]}) export class AppRoutingModule {}

Define your routes in the Routes array (each route in this array is a JavaScript object with two properties. The first attribute, path, defines the URL path for the route. The second property, component, defines the components that need to be displayed under the corresponding path)

2. Import AppRoutingModule in app.module.ts

Import {AppRoutingModule} from'. / app-routing.module'

3. Add these routes in app.component.html to control the display of navigation

Switch to the item list component to the personal Center component

Pieces.

Next, add tags to the template. This element informs Angular that you can update the view of the application with the components of the selected route. In the same way as a component, it acts as a placeholder to mark where the router should display the component.

Introduction of two important API in routing

ActivatedRoute

Used for {get routing information} to obtain routing information, which contains routing information such as routing parameters, static data. Specific methods can be found on ActivatedRoute's official website.

Import {Component, OnInit} from'@ angular/core';import {ActivatedRoute} from'@ angular/router' / / ① first introduces ActivatedRoute@Component ({selector: 'app-goods-list', templateUrl:'. / goods-list.component.html', styleUrls: ['. / goods-list.component.scss']}) export class GoodsListComponent implements OnInit {constructor (private route: ActivatedRoute) / / ② dependency injection this service) {} / / ③ in the initialization life cycle or url routing information public ngOnInit (): void {/ / the first way to get parameters const params = this.route.snapshot.params / / the second way to get parameters this.route.params.subscribe (params = > {console.log (params);});}}

The difference and use of the above two methods of obtaining parameters:

Route.snapshot:

You need to access the parameters directly, mainly get the initial value, and use snapshot without subscription.

Route.params.subscribe ():

Use params when you need to get every change of parameters or if you need to navigate continuously for many times.

Router

Is a module {providing navigation and manipulation of URL} that provides navigation and manipulation of URL. The specific methods provided can be found on the official website of Router. The methods commonly used in development are as follows. Details will be described in routing and passing parameters:

/ / before using, you need to introduce Router as a service class, import {Router} from'@ angular/router', in the component.

Navigate () this method supports the same type of parameters as the routerLink directive, so they do the same thing.

NavigateByUrl () absolute routing

The events method is called before each navigation; (only for the time being)

Routing parameters and getting

Two forms of routing parameters

1. Params (is /: id dynamic routing)

Usage scenario: for example, when we click on the item list link, we want to send the user information, or product category information, to the components of the item list through url.

/ / need to configure routing const routes: Routes = [{path: 'goodsList/:id', / / define the route name component: GoodsListComponent, / / specify the component displayed},]

2. QueryParams (in id=xx form)

Usage scenario: when we want to pass multiple parameters through url, we can choose to route parameters in this way

One parameter can be routed first by dynamic routing, but it is more convenient to use query for more than two parameters.

Three specific methods of transmitting parameters in routing

1. RouterLink

Single parameter:

You can also use this form when you switch to the commodity list component / / where / goodsListl is the route I set and path,id is the parameter to be passed / / multiple parameters, but it doesn't look intuitive enough, so this method is not recommended when you have multiple parameters.

Multiple parameters:

Switch to the personal center component / / parameter format can be self-organized into a variety of object

RouterLinkActive tracks whether the uplink route on the element is currently active. And allows you to specify one or more css classes to add this element when link routing is active.

2. Router.navigate

Navigate based on the array of commands provided and the starting point route. If no start route is specified, absolute navigation starts from the root route

Single parameter:

Public goToGoodsListPage (): void {/ / the first method this._router.navigate ([`/ goodsList/$ {this.id}`]); / / the second method achieves the same effect as the first method this._router.navigate (['/ goodsList', this.id]); calling this method in} / / html is equivalent to switching to the item list component using the routerLink attribute of the a tag

Multiple parameters:

Public goToPersonalCenterPage (): void {this._router.navigate (['/ personalCenter'], {queryParams: {name: 'zs', age: 16}});} / / html is called to switch to the personal Center component

3. Router.navigateByUrl

Navigation based on the URL provided must use an absolute path. The use of single and multiple parameters is the same as that of router.navigate.

/ / the first parameter passed is in the form of an array, while the first parameter of navigate is the way of the array / / his parameter is currently public goToPersonalCenterPage () concatenated on the url: void {this._router.navigateByUrl (`/ personalCenter?name=zs&age= 16`);} two ways to receive parameters in the route

1. Receive parameters of type params

Import {ActivatedRoute} from'@ angular/router';constructor (private _ route: ActivatedRoute,) {} public ngOnInit (): void {/ / the first way to get only the initial value const param = this.route.snapshot.params; / / the second dynamic method this.route.params.subscribe (params = > {console.log (params);});}

two。 Receive parameters of type queryParams

Import {ActivatedRoute} from'@ angular/router';constructor (private _ route: ActivatedRoute,) {} public ngOnInit (): void {/ / the first way to get only the initial value const queryParam = this.route.snapshot.queryParams; / / the second dynamic method this.route.queryParams.subscribe (params = > {console.log (params);});}

Route redirection

Application scenario: when in an application, you want the user to jump to a page by default, you need to use the get route redirection.

The composition of the redirection:

Path using redirect sourc

Redirect the target's component

PathMatch value to configure routing

{path:'', redirectTo:'/ personalCenter', pathMatch: 'full'}, / / redirect to `personalCenter`

{pathMatch} pathMatch is a string used to {specify route matching policy} to specify route matching policy. The options are prefix (the default) and full.

Prefix: starts with the specified path (that is, the value in path is the same as the beginning path entered by the user, for example, if path is "abc", then the user can enter / abc and / abc/a, but entering / abcd is not allowed); if path is empty, then all routes will match to this page

Full: exactly the same as the specified path (this is exactly the same as the path required by path, for example, if path is' abc', then user input / abc, / abc/ is OK / abcd,/abc/d is not allowed); if path is empty, it will match to this page only if nothing is added after localhost:4200.

Routing order

Router uses the strategy of "{first come, first served}" when matching routes, so you should put {specific static routes} specific static routes first, and then you can place empty path routes that match {default routes} default routes, and {wildcard} wildcard routes are the last (he can match so routes, Router will select him when no other routes are matched)

Const routes: Routes = [/ / static route {path: 'goodsList/:id', component: GoodsListComponent,}, {path:' personalCenter', component: PersonalCenterComponent,}, / / default empty path route {path:', redirectTo:'/ personalCenter', pathMatch: 'full'}, / / wildcard route {path:' * *', component: PageNotFoundComponent},]

Routing nesting

When the application becomes more complex, you may need to create some relative routes outside the root component, which become child routes, which means that a second {} needs to be added to the project because it is another {} outside the AppComponent.

Scenario: in the page of personal Center, we need to jump to his two sub-pages, namely, {personal configuration page} personal configuration page and {personal details page} personal details page. The specific code implementation is as follows:

Import {NgModule} from'@ angular/core';import {Routes, RouterModule} from'@ angular/router';import {GoodsListComponent} from'. / goods-list/goods-list.component';import {PersonalCenterComponent} from'. / personal-center/personal-center.component';import {PersonalSettingComponent} from'. / personal-setting/personal-setting.component';import {PersonalDetailComponent} from'. / personal-detail/personal-detail.component' Const routes: Routes = [{path: 'goodsList/:id', component: GoodsListComponent,}, {path:' personalCenter', component: PersonalCenterComponent, children: [/ / mainly because a children array is added here Used to store child routes {path: 'personalDetail', component: PersonalDetailComponent,}, {path:' personalSetting', component: PersonalSettingComponent,},]}, {path:', redirectTo:'/ personalCenter', pathMatch: 'full'},] / / in the html of the personal center, it needs to be added to specify the location of the sub-page to be displayed. This is the personal center page to switch from the personal details page to the personal configuration page.

Child routes, like other routes, require both path and component. The only difference is that you put the child route in the children array of the parent route.

Routing lazy loading

You can configure routing definitions to lazily load modules, which means that Angular only loads these modules when needed, rather than loading all of them when the application {startup} starts.

1. Add a module file to the previous two page components, and then use loadChildren instead of component for configuration in routes

Import {NgModule} from'@ angular/core';import {Routes, RouterModule} from'@ angular/router' Const routes: Routes = [{path: 'goodsList/:id', loadChildren: () = > import ('. / goods-list/goods-list.module'). Then (m = > m.GoodListModule)}, {path: 'personalCenter', loadChildren: () = > import ('. / personal-center/personal-center.module'). Then (m = > m.PersonalCenterModule)} {path:', redirectTo:'/ personalCenter', pathMatch: 'full'},] The @ NgModule ({/ / forRoot () method creates a NgModule that contains all instructions, the given route, and the Router service itself. Imports: [RouterModule.forRoot (routes)], exports: [RouterModule]}) export class AppRoutingModule {}

2. Add a routing module file to the previous two page components, and add a route to that component.

Import {NgModule} from'@ angular/core';import {Routes, RouterModule} from'@ angular/router';import {GoodsListComponent} from'. / goods-list.component';const routes: Routes = [{path:', component: GoodsListComponent},]; @ NgModule ({imports: [RouterModule.forChild (routes)], exports: [RouterModule]}) export class GoodsListRoutingModule {}

Routing guards (only know)

Use routing guards to prevent users from navigating to certain parts of the application without authorization. For more information, please introduce the official website of Mobile routing Guards.

Use CanActivate to handle navigating to a route. / / when entering the route

Use CanActivateChild to handle navigating to a child route.

Use CanDeactivate to handle departures from the current route. / / when leaving the route

Use Resolve to get routing data before the route is activated.

Use CanLoad to handle asynchronous navigation to a feature module. CanActivate will still load a module, and canload will not load it when the condition is not met

Export class TestGuard implements CanActivate {canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {/ / Logic to determine whether a route can be entered} {path: 'test-path', component: TestComponent, canActivate: [TestGuard], / / use route guard guard}

Routing events (only known)

Router emits navigation events through the Router.events attribute during each navigation. The scope of these events runs through multiple points in time between the beginning and end of the navigation. If you want to know more, please move.

Detailed introduction of routing events on the official website

Https://angular.cn/guide/router-reference#router-events

Introduction of forms in Angular

The difference between responsive form and template-driven form

Responsive template-driven building form model display, creating implicit in component classes, instructions to create data models structured and immutable (observable objects) unstructured and variable (data two-way binding) data flow synchronous asynchronous form validation function instructions

Common basic classes for common forms

Both responsive and template-driven forms are based on the following basic classes.

The FormControl instance is used to track the value and validation status of a single form control.

FormGroup is used to track the value and status of a group of form controls.

FormArray is used to track the values and status of an array of form controls. (understand)

Template-driven form

{dependency} relies on the {instruction} instructions in the template to create and manipulate the underlying object model. It is mainly used to add simple forms, which is easy to use, but not as extensible as responsive forms. When the control value is updated, the relevant property value is changed to the new value.

Create form name: password: submit template driven form to verify input name: password: the length of the submitted name cannot be less than 2 digits and the password cannot be empty

Responsive form (key points)

Provides direct and explicit access to the {underlying form object model}. They are more robust than template-driven forms, and they are more extensible, reusable, and testable. And control updates are more efficient because instances of FormControl always return a new value instead of updating the existing data model, and if the form is a key part of your application or is highly extensible, use a responsive form

Use responsive forms

1. Introduce the responsive form module into the module file.

Import {ReactiveFormsModule} from'@ angular/forms'

2. Introduce a form group into the component

Import {FormGroup, FormControl} from'@ angular/forms'

3. Create an instance of FormGroup and associate the FormGroup model to the view

This.profileForm = new FormGroup ({name: new FormControl (''), password: new FormControl (''),}); First Name: Last Name: submit form nesting

A form group can accept both {single form control instance} a single form control instance and other form group instances as its {child control} child controls. This makes complex form models easier to maintain and logically group them together.

1. Create a nested group of forms.

This.profileForm = new FormGroup ({name: new FormControl ('', [Validators.required]), password: new FormControl (''), / / nesting an address form group address: new FormGroup ({street: new FormControl (''), city: new FormControl (''),})

2. Group this nested form in the template.

First Name: Last Name: / / use formGroupName to declare the new form group Address Street: City: the field that submits the state of the form validation control

Before we learn about form validation, let's take a look at some of the {status fields} status fields provided by angular for the form that can help users decide at which stages to do form validation.

Touched and untouched

It is used to determine whether the user has obtained focus, touched=true; untouched=false if it has, and touched=false; untouched=true if it has never been obtained.

Pristine and dirty

It is used to determine whether the user has manipulated the field. Dirty indicates that the user has manipulated the form element, and pristine indicates that the form element has not been manipulated.

Valid and invalid

To determine whether the form element is valid, when there are multiple verification conditions on the form element, only all the verification conditions meet the verification requirements valid is true, as long as one verification condition is not met, then the attribute value of invalid is true.

CSS class for the state of the control

Angular automatically maps many of the {control properties} control properties as the {CSS class} CSS class to the {element} element where the control resides. You can use these classes to add styles to form {control elements} control elements according to the form {status} status.

. ng-valid

. ng-invalid

. ng-pending

. ng-pristine

. ng-dirty

. ng-untouched

. ng-touched

Scenario: for example, when the control does not meet the verification conditions, the border of the control is displayed in red ~ implemented as follows:

.ng-touched:not (form) {& .ng-invalid:not (form) {/ / this is a way of writing scss border: 1px solid red}} form validation steps

1. Import a validator function into the form component. Angular provides specific built-in validators. Please refer to the official website of the form validator.

The main built-in verifiers provided by import {Validators} from'@ angular/forms';// angular are: min max required email minLength maxLength pattern...

2. Add this validator to the corresponding field in the form.

Scenario: the contents that need to be verified are: the ① name cannot be empty; the ② password cannot be empty and the minimum length cannot be less than 4; the street in the ③ address cannot be empty.

This.profileForm = new FormGroup ({name: new FormControl ('', [Validators.required]), password: new FormControl ('', [Validators.required, Validators.minLength (4)]), address: new FormGroup ({street: new FormControl ('', [Validators.required]), city: new FormControl (''),}))

3. Reminder logic of error messages in the template

Name: first name is required

Password: the number of digits of the password cannot be less than four.

Password cannot be empty

Address Street: Street cannot be empty City: submit custom form validator

Scenario: users want to verify whether the format of the mobile phone number is entered correctly when filling in the mobile phone number, so they can do this through a custom function

Public ngOnInit (): void {this.profileForm = new FormGroup ({phone: new FormControl (', [this.mobileValidator])});} public mobileValidator = (control: FormControl): any = > {const value = control.value; / / regular const mobileReg = / ^ 0? (13 [0-9] | 15 [012356789] | 17 [013678] | 18 [0-9] | 14 [57]) [0-9] {8} $/; const result = mobileReg.test (value) / / valid values return null, and if invalid, the error object for verification is returned. The verification object is a verification key attribute named mobileFormat. The value can generally be any value / / mobileFormat will be used again when return result is used to get error messages in the template? Null: {mobileFormat: {info: 'incorrect phone format'};} / / use {{profileForm?.get ('phone'). Errors | json}} / / the error message defined in the custom function can be printed out in the incorrect phone format.

Submit how to update form data

Use the setValue () method to set a new value for a single control. The setValue () method strictly follows the structure of the form group and replaces the value of the control as a whole.

Using the patchValue () method, you can replace the form model with any property defined in the object.

Use FormBuilder services to build controls

FormBuilder services provide some {convenient methods} convenient ways to generate form controls. FormBuilder uses the same method behind the scenes to create and return these instances, but it is easier to use.

Services have three methods: control (), group (), and array (). These methods are factory methods that are used to generate FormControl, FormGroup, and FormArray in the component class, respectively.

1. Introduce the FormBuilder class into the component and inject services

Import {FormBuilder} from'@ angular/forms';constructor (private fb: FormBuilder) {}

two。 Generate form content

This.profileForm = this.fb.group ({name: ['], password: [']}); / equivalent to this.profileForm = new FormGroup ({name: new FormControl (''), password: new FormControl (''),}); Cross-field cross-validation (only understand) const heroForm = new FormGroup ({'name': new FormControl (),' alterEgo': new FormControl (), 'power': new FormControl ()}, {validators: identityRevealedValidator}) Export const identityRevealedValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null = > {const name = control.get ('name'); const alterEgo = control.get (' alterEgo'); return name & & alterEgo & & name.value = = alterEgo.value? {identityRevealed: true}: null;}; this is all the content of the article "sample Analysis of routes and forms in Angular". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report