一、本項目是基於以前文章續寫的。css
用到了哪些html
一、路由,子路由的使用,引入——定義Routes——router-outlet——routerLink——routerLinkActive
二、(click)指令,綁定事件
三、[ngClass]指令,綁定樣式python
npm i --save @angular/router
官方網址:https://angular.io/guide/routernpm
要使用路由,咱們須要在 app.module.ts 模塊中,導入 RouterModule 。具體以下:app
import { RouterModule } from '@angular/router';
imports: [ BrowserModule, FormsModule, HttpModule, RouterModule, WeUIModule ],
這樣還不行,還要定義和添加路由,修改以下:ide
import { Routes, RouterModule } from '@angular/router';
export const ROUTES: Routes = [ { path: '#', component: AccountingComponent }, { path: 'count', component: CountComponent } ];
imports: [ BrowserModule, FormsModule, HttpModule, WeUIModule, RouterModule.forRoot(ROUTES) ],
這樣就定義好路由了,還須要在頁面上指定路由的區域。修改菜單menu.component.html以下:
routerLink 是路由地址,routerLinkActive的做用是,當 a 元素對應的路由處於激活狀態時,weui-bar__item_on類將會自動添加到 a 元素上。ui
<weui-tabbar> <a routerLink="#" routerLinkActive="weui-bar__item_on" class="weui-tabbar__item"> <span class="weui-tabbar__icon"> <i class="fa fa-edit"></i> </span> <p class="weui-tabbar__label">記帳</p> </a> <a routerLink="/count" routerLinkActive="weui-bar__item_on" class="weui-tabbar__item"> <span class="weui-tabbar__icon"> <i class="fa fa-bar-chart"></i> </span> <p class="weui-tabbar__label">統計</p> </a> </weui-tabbar>
app.component.html 修改以下:
router-outlet爲路由內容呈現的容器。this
<router-outlet></router-outlet> <app-menu></app-menu>
能夠看出存在問題,進入時沒有默認頁面,必須點擊後纔會到對應頁面,能夠將路由中#改成空,能夠實現默認進入記帳頁面,可是routerLinkActive就失去效果了,記帳按鈕就會一直亮着。不夠後面咱們用動態綁定class的方法來代替routerLinkActive。spa
咱們當初設計統計有兩個頁面,按年統計,和按月統計。如今來完成這個。
加入子路由設計
export const ROUTES: Routes = [ { path: '#', component: AccountingComponent }, { path: 'count', component: CountComponent, children: [ { path: '', component: CountMonthComponent }, { path: 'year', component: CountYearComponent } ] } ];
添加count.component.html
<div class="weui-panel__hd"> <span>當前記帳金額爲:</span> <em>123456</em> </div> <weui-navbar style="position: relative"> <a routerLink="/count" class="weui-navbar__item"> <h4>月</h4> </a> <a routerLink="/count/year" class="weui-navbar__item" > <h4>年</h4> </a> </weui-navbar> <div> <router-outlet></router-outlet> </div>
這裏咱們沒有用到routerLinkActive,如今咱們用動態樣式來實現
count.component.ts裏面咱們添加一個標記
export class CountComponent implements OnInit { activeIndex = 0; // 當前激活標記 constructor() { } ngOnInit() { } setActive(i) { // 設置標記 this.activeIndex = i; } }
count.component.html 修改
<weui-navbar style="position: relative"> <a routerLink="/count" (click)="setActive(1)" class="weui-navbar__item" [ngClass]="{'weui-bar__item_on':activeIndex == 1}"> <h4>月</h4> </a> <a routerLink="/count/year" (click)="setActive(2)" class="weui-navbar__item" [ngClass]="{'weui-bar__item_on':activeIndex == 2}"> <h4>年</h4> </a> </weui-navbar>
修改下count.component.css裏的樣式
.weui-panel__hd{ padding:18px; text-align: center; } .weui-panel__hd span{ font-size: 14px; } .weui-panel__hd em{ font-size: 20px; color: #09bb07; display: inherit; letter-spacing: 1px; }