天天看點

Angular學習之---路由基礎(一)

1.建立帶路由配置的項目

ng new router –routing 會自動生成app-routing.module.ts檔案

相關對象介紹:

Angular學習之---路由基礎(一)

簡單解釋:

Routes用法:path:‘user’,component:XXXComponent 指定顯示的元件 注意(path不能用/XX,出現路徑問題)

RouterOutlet:插座 使子元件在父模闆中指定位置顯示(html)

RouterLink:在父模闆中通過a标簽指向其他元件(html)

Router:元件中調用navigate()方法改變導航欄中的位址(component)

ActivatedRoute:儲存傳遞路由時的參數資訊和位址

需求:點選按鈕1頁面顯示内容 ‘按鈕1text’點選按鈕2頁面顯示 ‘按鈕2text’

1.建立元件showOne和showTwo

2.在html中設定不同的text以便區分

3.在app-routing.module檔案中設定路徑

const routes: Routes = [
//預設 path:'**'時為預設路由
  {path:'',component:ShowOneComponent},
  {path:'test',component:ShowTwoComponent}
];
           

4.app.component.html檔案

//預設路徑 目前路徑為根路徑 若為./表示為子路徑 (在child子路徑中會用到)routerLink可以傳遞路徑和參數
<a [routerLink]="['/']"></a>
<a [routerLink]="['/test']"></a>
<router-outlet></router-outlet>
           
Angular學習之---路由基礎(一)
Angular學習之---路由基礎(一)

5.通過Router的negative方法跳轉同樣可以實作此功能

在app.component.html檔案添加個button

6.app.component.ts

constructor(private router:Router){}

  showText(){
    console.log("rrrrr");
    this.router.navigate(['/test']);
  }