iT邦幫忙

0

Angular#4 專案:路由 建置

joor 2021-05-02 00:10:191260 瀏覽
  • 分享至 

  • xImage
  •  

Angular

[目標]

啟動程式先導入Login元件
https://ithelp.ithome.com.tw/upload/images/20210501/201371342VoS7P6AKL.png


1. 新增元件、模組

  • Syntax:ng help可以查詢
ng generate component [component_name]
ng generate module [module_name]

新增login元件、home元件 範例:
ng g c login
ng g c home
新增app-routing模組 範例:
ng g m app-routing

https://ithelp.ithome.com.tw/upload/images/20210501/20137134oGn6B57JXx.png


2. VSCode 撰寫

  • app-routing
    app-routing.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// 引用的模組、元件
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from '../home/home.component';
import { LoginComponent } from '../login/login.component';
// 建立路由規則
const appRoutes: Routes = [
  { path: '', redirectTo:'login',pathMatch:'full' },
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent },
  { path: '**', redirectTo:''}
]
// 模組設定
@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(
      appRoutes, { enableTracing: false }
    )
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule { }
  • app
    app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// 引用的模組、元件
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { AppRoutingModule } from './app-routing/app-routing.module';
// 模組設定
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<router-outlet></router-outlet>

3. 啟動專案

ng serve --open --port [XXXX]

範例ng serve --open --port 9985


4. 完成

https://ithelp.ithome.com.tw/upload/images/20210501/201371344j4xgO7TDq.png

上一篇
下一篇


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言