angular - router.navigate navigerar inte till definierad sökväg html


Jag är ny på Angular. Skapar enkel navigation från en komponent till en annan. Använder router.navigate-metoden för navigation.

När en knapp klickas på ändras URL:en men den specifika komponentens HTML-sida visas inte.

this.router.navigate(['login']);

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { LoginComponent } from './Components/ProfileComponents/login/login.component';
import { Routes, RouterModule } from '@angular/router';
import { TestrouteComponent } from './testroute/testroute.component';


const appRoutes: Routes = [
  { path: 'login', component: TestrouteComponent }
];
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    TestrouteComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes, { enableTracing: true })
  ],
  exports: [RouterModule],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private router: Router, private _activateRoute: ActivatedRoute) {}
  title = 'app';
  testRouting() {
  this.router.navigate(['login']);
  }
}

app.component.html

<div style="text-align:center">
  <h1>
    Welcome
  </h1>
</div>
<h2>Here are some links to help you start: </h2>
<button (click)="testRouting()">test</button>

testroute.component.html

<p>
  testroute works!
</p>

testroute.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-testroute',
  templateUrl: './testroute.component.html',
  styleUrls: ['./testroute.component.css']
})
export class TestrouteComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

ren kod vill bara kolla router.navigate-funktionen. Inte säker på exakt vad jag saknar här.

Svar #1

Jag tror att du glömde att lägga till din <router-outlet></router-outlet> i din app.component.html-fil.

Det kommer att lägga till komponenten som definieras i din routermodul när URL:en matchar en viss rutt. Så i ditt fall kommer det att lägga till TestrouteComponent.

Till exempel i din app.component.html

<div style="text-align:center">
  <h1>
    Welcome
  </h1>
</div>
<h2>Here are some links to help you start: </h2>
<button (click)="testRouting()">test</button>
<router-outlet></router-outlet>

Observera att dina h1-, h2- och knapp-element fortfarande kommer att vara synliga även när rutten ändras när HTML är uppsatt så här.