angularHow to implement tab bar switching? This article will introduce to you how to implement tab bar switching in angular4. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related tutorial recommendations: "angular Tutorial"
Management system tab switching page is a common requirement, which is roughly as follows :
Click on the left menu, the corresponding tab will be displayed on the right, and then different 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
But I couldn’t achieve it, so I was wondering if a simple tab page is so difficult?
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 had an idea, and it took me half a day to finally implement anguar 4 tab The general idea of switching pages 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. Register the strategy into 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 implement the reuse strategy, but to achieve the first rendering, we still need to do some other work
3. Define the route 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]); } }
app.html code is as follows:
<div class="row"> <div 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> </div> <div class="col-md-8"> <div 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> </div> <router-outlet></router-outlet> </div> </div>
The overall effect is as follows:
Finally click the menu to display the corresponding label selection, you can switch the editing content, when closing the label, click the menu again to reload content.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of Introduction to the method of implementing tab switching in angular4. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.