search
HomeWeb Front-endJS TutorialSharing the method of implementing tab bar switching in angular4

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 component. The app.component code is as follows:


##

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 === &#39;primary&#39;)
   .mergeMap(route => route.data)
   .subscribe((event) => {
    //路由data的标题
    let title = event[&#39;title&#39;];
    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([&#39;/&#39;+menu.module]);
 }
}
import { Component } from &#39;@angular/core&#39;;
import { SimpleReuseStrategy } from &#39;./SimpleReuseStrategy&#39;;
import { ActivatedRoute, Router, NavigationEnd } from &#39;@angular/router&#39;;
import { Title } from &#39;@angular/platform-browser&#39;;
import &#39;rxjs/add/operator/filter&#39;;
import &#39;rxjs/add/operator/map&#39;;
import &#39;rxjs/add/operator/mergeMap&#39;;

@Component({
 selector: &#39;app-root&#39;,
 styleUrls:[&#39;app.css&#39;],
 templateUrl: &#39;app.html&#39;,
 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 === &#39;primary&#39;)
   .mergeMap(route => route.data)
   .subscribe((event) => {
    //路由data的标题
    let title = event[&#39;title&#39;];
    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([&#39;/&#39;+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:

Finally click on the menu to display the corresponding When the label is selected, you can switch the editing content. When the label is closed, click the menu again to reload the content.

Related recommendations:

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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 Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

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.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

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.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

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 notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

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...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)