2017-07-03 65 views
1

我做了一個Angular4組件,它生成的頁面有一個導航到另一個頁面的按鈕。我沒有得到任何錯誤和pageUrl更改,但頁面內容保持不變。Angular4中的路徑導航沒有反應

這裏是我的代碼:

app.component.ts

import { Component } from '@angular/core'; 
import { Router } from "@angular/router"; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 

export class AppComponent { 

constructor(private router: Router){} 

username = ""; 
password = ""; 
log = function() { 
    if (this.username != "" && this.password != "") { 
    console.log(this.username + " " + this.password); 
    this.router.navigate(['/dashboard']); 
    } 
} 
} 

app.module.ts

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { RouterModule } from '@angular/router'; 
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 

import { AppComponent } from './app.component'; 
import { DashboardComponent } from './dashboard/dashboard.component'; 


@NgModule({ 
    declarations: [ 
    AppComponent, 
    DashboardComponent, 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    RouterModule.forRoot([ 
    { 
    path: 'dashboard', 
    component: DashboardComponent 
    } 
] 
) 
], 
providers: [], 
bootstrap: [AppComponent], 
}) 
export class AppModule { 
} 

app.component.html

<div class="outer-container"> 
    <div class="inner-container"> 
    <div class="centered-content"> 
    <div class="center"><img src="../favicon.png"></div> 
     <label class="addText"> Username: </label><input [(ngModel)] 
     ="username" class="addText"><br> 
     <label class="addText"> Password: </label><input [(ngModel)] 
     ="password" type="password" class="addText"><br> 
     <div class="center"><button (click) ="log()">Log in</button></div> 
    </div> 
    </div> 
</div> 

回答

1

顯示組件結果要達到你想要什麼,有app.component只包括路由器插座:

@Component({ 
    selector: 'app-root', 
    template: ` 
     <!-- Views go here--> 
     <router-outlet></router-outlet>  
    `, 
}) 
export class AppComponent { } 

然後爲您想要的每個視圖分別創建一個組件。所以在你的情況下,你想創建一個LoginComponent,然後從那裏路由到DashboardComponent

PS當然這是可擴展的,您可以在AppComponent html或其他任何內容中添加標頭組件標籤等等。但只是爲了展示這個簡單的用例。

+0

所以這就是爲什麼你得到一個appcomponent,謝謝,我現在得到它 – fangio

+0

沒問題,很高興我可以幫助!當我開始時,我也對如何構建一個組件的路由器感到困惑,所以我完全可以把它們聯繫起來:) – Alex

0

你需要指定顯示DashboardComponent
添加這個標籤告訴角的位置在哪裏,從路由器

<router-outlet></router-outlet>

+1

欲瞭解更多信息,請閱讀https://angular.io/guide/router –

+0

我想改變整個頁面,而不是將其添加到頁面... – fangio

+0

角度是單頁面應用程序,您不能切換頁面:) –