【问题标题】:Route navigation in Angular4 not reactingAngular4中的路线导航没有反应
【发布时间】:2017-07-03 13:34:57
【问题描述】:

我制作了一个 Angular4 组件,它生成的页面有一个按钮可以导航到另一个页面。我没有收到任何错误,并且 pageUrl 发生了变化,但页面内容保持不变。

这是我的代码:

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>

【问题讨论】:

    标签: html angular routing


    【解决方案1】:

    要实现你想要的,让app.component 只包含路由器插座:

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

    然后为您想要的每个视图创建一个单独的组件。所以在你的情况下,你想创建一个LoginComponent,然后从那里路由到DashboardComponent

    PS 当然,这是可扩展的,您可以在AppComponent html 中添加标题组件标签,或者其他任何内容等等。但只是为了展示这个简单的用例。

    【讨论】:

    • 这就是为什么你得到一个appcomponent,谢谢,我现在明白了
    • 没问题,很高兴能帮上忙!当我开始时,我也对如何构建组件的路由感到困惑,所以我可以完全理解:)
    【解决方案2】:

    您需要指定显示仪表板组件的位置
    添加此标签以告诉 Angular 显示路由器组件结果的位置

    &lt;router-outlet&gt;&lt;/router-outlet&gt;

    【讨论】:

    • angular 是单页应用,不能在页面之间切换 :)
    • 如何重新生成整个页面?
    • 重新生成整个页面没有任何意义,你有组件,这些组件在一页中代表应用程序。
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 2020-11-13
    • 2020-04-07
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多