![](/img/trans.png)
[英]how to do data sharing of service among two different components in Angular 2
[英]How to develop tabs in angular7 which switch among two different components?
您可以擁有一個包含所有 3 個組件的容器,並向每個將決定是否顯示它的組件添加ngIf
。
當然,您始終可以使用 Angular Material Tabs: https : //material.angular.io/components/tabs/overview
假設我們有 4 個組件(app.component、a.component、b.component、c.component)
檢查以下網址中的完整代碼https://stackblitz.com/edit/angular-gerrxm
我不使用 Angular Material,但您需要使用路由器來導航到每個。
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', loadChildren: './home/home.module#HomeModule' },
{ path: 'mycomp1', component: MyComp1Component },
{ path: 'mycomp2', component: MyComp2Component },
{ path: 'mycomp3', component: MyComp3Component }
];
html文件:
<div class="tab">
<button class="tablinks" routerLink="/tab1">Tab 1</button>
<button class="tablinks" routerLink="/tab2">Tab 2</button>
<button class="tablinks" routerLink="/tab3">Tab 3</button>
</div>
Using router method in component
<div class="tab">
<button class="tablinks" (click)="setTab('tab1')">Tab 1</button>
<button class="tablinks" (click)="setTab('tab2')">Tab 2</button>
<button class="tablinks" (click)="setTab('tab3')">Tab 3</button>
</div>
<router-outlet></router-outlet>
Ts 文件:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(
private router: Router
) {}
setTab(tabname: string) {
this.router.navigate([`/${tabname}`]);
}
}
CSS :
body {font-family: Arial;}
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: block;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.