This article mainly introduces examples of how to implement tab bar switching in angular4. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Management system tab switching page is a common requirement, roughly as follows:
Click on the left menu, the corresponding tab will be displayed on the right, and then different The tabs can be edited at the same time, and the information will not be lost when switching!
Use PHP or .net, Java development technology, probably switch the display, and then add an ifram to do it, or load the information through ajax to display the corresponding layer.
But if you use angular How to achieve this? The first idea is, can it be implemented using the same ifarm?
The second thing that comes to mind is that the routing socket looks like this
Copy code The code is as follows:
But it didn’t work Implementation, so I wonder if it is so difficult to create a simple tab page?
Or is there really no simple way?
For a long time, I didn’t care about this
Because I knew that my understanding and learning of angular was not enough, so I put it down for a long time until I saw it on Zhihu An article
Angular routing reuse strategy
So I came up with an idea, and it took me half a day to finally implement anguar 4 tab switching page. The general idea is as follows:
1. Implement the RouteReuseStrategy interface to customize a routing utilization strategy
SimpleReuseStrategy.ts code is as follows:
import { RouteReuseStrategy, DefaultUrlSerializer, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router'; export class SimpleReuseStrategy implements RouteReuseStrategy { public static handlers: { [key: string]: DetachedRouteHandle } = {} /** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */ public shouldDetach(route: ActivatedRouteSnapshot): boolean { return true; } /** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */ public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { SimpleReuseStrategy.handlers[route.routeConfig.path] = handle } /** 若 path 在缓存中有的都认为允许还原路由 */ public shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!route.routeConfig && !!SimpleReuseStrategy.handlers[route.routeConfig.path] } /** 从缓存中获取快照,若无则返回nul */ public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { if (!route.routeConfig) { return null } return SimpleReuseStrategy.handlers[route.routeConfig.path] } /** 进入路由触发,判断是否同一路由 */ public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig } }
2 , the strategy is registered in the module:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { CommonModule as SystemCommonModule } from '@angular/common'; import { AppComponent } from './app.component'; import { AppRoutingModule,ComponentList } from './app.routing' import { SimpleReuseStrategy } from './SimpleReuseStrategy'; import { RouteReuseStrategy } from '@angular/router'; @NgModule({ declarations: [ AppComponent, ComponentList ], imports: [ BrowserModule, AppRoutingModule, FormsModule, SystemCommonModule ], providers: [ { provide: RouteReuseStrategy, useClass: SimpleReuseStrategy } ], bootstrap: [AppComponent] }) export class AppModule { }
The above two steps basically realize the reuse strategy, but to realize the first rendering, it still needs to be Do some other work
3. Define routing and add some data. The data routing code is as follows:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AboutComponent } from './home/about.component' import { HomeComponent } from './home/home.component' import { NewsComponent } from './home/news.component' import { ContactComponent } from './home/contact.component' export const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full', }, { path: 'home', component: HomeComponent,data: { title: '首页', module: 'home', power: "SHOW" } }, { path: 'news',component: NewsComponent ,data: { title: '新闻管理', module: 'news', power: "SHOW" }}, { path: 'contact',component: ContactComponent ,data: { title: '联系我们', module: 'contact', power: "SHOW" }}, { path: 'about', component: AboutComponent,data: { title: '关于我们', module: 'about', power: "SHOW" } }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } export const ComponentList=[ HomeComponent, NewsComponent, AboutComponent, ContactComponent ]
4. Implement routing events in the
##
import { Component } from '@angular/core'; import { SimpleReuseStrategy } from './SimpleReuseStrategy'; import { ActivatedRoute, Router, NavigationEnd } from '@angular/router'; import { Title } from '@angular/platform-browser'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; @Component({ selector: 'app-root', styleUrls:['app.css'], templateUrl: 'app.html', providers: [SimpleReuseStrategy] }) export class AppComponent { //路由列表 menuList: Array<{ title: string, module: string, power: string,isSelect:boolean }>=[]; constructor(private router: Router, private activatedRoute: ActivatedRoute, private titleService: Title) { //路由事件 this.router.events.filter(event => event instanceof NavigationEnd) .map(() => this.activatedRoute) .map(route => { while (route.firstChild) route = route.firstChild; return route; }) .filter(route => route.outlet === 'primary') .mergeMap(route => route.data) .subscribe((event) => { //路由data的标题 let title = event['title']; this.menuList.forEach(p => p.isSelect=false); var menu = { title: title, module: event["module"], power: event["power"], isSelect:true}; this.titleService.setTitle(title); let exitMenu=this.menuList.find(info=>info.title==title); if(exitMenu){//如果存在不添加,当前表示选中 this.menuList.forEach(p => p.isSelect=p.title==title); return ; } this.menuList.push(menu); }); } //关闭选项标签 closeUrl(module:string,isSelect:boolean){ //当前关闭的是第几个路由 let index=this.menuList.findIndex(p=>p.module==module); //如果只有一个不可以关闭 if(this.menuList.length==1) return ; this.menuList=this.menuList.filter(p=>p.module!=module); //删除复用 delete SimpleReuseStrategy.handlers[module]; if(!isSelect) return; //显示上一个选中 let menu=this.menuList[index-1]; if(!menu) {//如果上一个没有下一个选中 menu=this.menuList[index+1]; } // console.log(menu); // console.log(this.menuList); this.menuList.forEach(p => p.isSelect=p.module==menu.module ); //显示当前路由信息 this.router.navigate(['/'+menu.module]); } } import { Component } from '@angular/core'; import { SimpleReuseStrategy } from './SimpleReuseStrategy'; import { ActivatedRoute, Router, NavigationEnd } from '@angular/router'; import { Title } from '@angular/platform-browser'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; @Component({ selector: 'app-root', styleUrls:['app.css'], templateUrl: 'app.html', providers: [SimpleReuseStrategy] }) export class AppComponent { //路由列表 menuList: Array<{ title: string, module: string, power: string,isSelect:boolean }>=[]; constructor(private router: Router, private activatedRoute: ActivatedRoute, private titleService: Title) { //路由事件 this.router.events.filter(event => event instanceof NavigationEnd) .map(() => this.activatedRoute) .map(route => { while (route.firstChild) route = route.firstChild; return route; }) .filter(route => route.outlet === 'primary') .mergeMap(route => route.data) .subscribe((event) => { //路由data的标题 let title = event['title']; this.menuList.forEach(p => p.isSelect=false); var menu = { title: title, module: event["module"], power: event["power"], isSelect:true}; this.titleService.setTitle(title); let exitMenu=this.menuList.find(info=>info.title==title); if(exitMenu){//如果存在不添加,当前表示选中 this.menuList.forEach(p => p.isSelect=p.title==title); return ; } this.menuList.push(menu); }); } //关闭选项标签 closeUrl(module:string,isSelect:boolean){ //当前关闭的是第几个路由 let index=this.menuList.findIndex(p=>p.module==module); //如果只有一个不可以关闭 if(this.menuList.length==1) return ; this.menuList=this.menuList.filter(p=>p.module!=module); //删除复用 delete SimpleReuseStrategy.handlers[module]; if(!isSelect) return; //显示上一个选中 let menu=this.menuList[index-1]; if(!menu) {//如果上一个没有下一个选中 menu=this.menuList[index+1]; } // console.log(menu); // console.log(this.menuList); this.menuList.forEach(p => p.isSelect=p.module==menu.module ); //显示当前路由信息 this.router.navigate(['/'+menu.module]); } }The code of app.html is as follows:
<p class="row"> <p class="col-md-4"> <ul> <li><a routerLinkActive="active" routerLink="/home">首页</a></li> <li><a routerLinkActive="active" routerLink="/about">关于我们</a></li> <li><a routerLinkActive="active" routerLink="/news">新闻中心</a></li> <li><a routerLinkActive="active" routerLink="/contact">联系我们</a></li> </ul> </p> <p class="col-md-8"> <p class="crumbs clearfix"> <ul> <ng-container *ngFor="let menu of menuList"> <ng-container *ngIf="menu.isSelect"> <li class="isSelect"> <a routerLink="/{{ menu.module }}">{{ menu.title }}</a> <span (click)="closeUrl(menu.module,menu.isSelect)">X</span> </li> </ng-container> <ng-container *ngIf="!menu.isSelect"> <li> <a routerLink="/{{ menu.module }}">{{ menu.title }}</a> <span (click)="closeUrl(menu.module,menu.isSelect)">X</span> </li> </ng-container> </ng-container> </ul> </p> <router-outlet></router-outlet> </p> </p>The overall effect is as follows:
How to achieve the switching effect of the tab bar
Realize the switching effect of the tab bar in the DOM
php implements reading and writing tab-delimited files
The above is the detailed content of Sharing the method of implementing tab bar switching in angular4. For more information, please follow other related articles on the PHP Chinese website!

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)