簡體   English   中英

如何在angular7中開發在兩個不同組件之間切換的選項卡?

[英]How to develop tabs in angular7 which switch among two different components?

我在 angular 7 項目中生成了三個不同的組件

ng g c mycomp1
ng g c mycomp2
ng g c mycomp3

現在我想在mycop1組件中開發一個選項卡,如下所示

標簽圖片

通過單擊第一個選項卡,它應該顯示 HTML 或呈現來自同一組件的內容。
通過單擊我需要從 mycomp2 組件(來自不同組件)呈現內容的第二個選項卡,
與從 mycomp3 組件渲染所需的第三個選項卡類似。 請幫助我如何繼續這樣做,
謝謝

您可以擁有一個包含所有 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM