gpt4 book ai didi

angular2-routing - Angular 4路由不起作用

转载 作者:行者123 更新时间:2023-12-03 15:25:54 25 4
gpt4 key购买 nike

我已经检查了有关此问题的堆栈溢出答案,但是似乎都没有意义,我创建了两个组件page1和page2。并在module.ts中声明一条路由

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


import { AppComponent } from './app.component';
import { Page1Component } from './page1/page1.component';
import { Page2Component } from './page2/page2.component';


@NgModule({
declarations: [
AppComponent,
Page1Component,
Page2Component
],
imports: [
BrowserModule,
RouterModule.forRoot([
{path:'page1', component:Page1Component},
{path:'page2', component:Page2Component}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

而我的page1 html如下
<p>
page1 works!

<button (click)= 'OnbtnClick()'>Route to Page2</button>
</p>

组件ts如下
import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router';

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

constructor(private _router:Router) { }

ngOnInit() {
}

OnbtnClick()
{
let abc =this._router.navigate(['/page2'])

}
}

但是在单击按钮时,“Url”正在更改,但是 View 保持不变,appcomponent.html如下。
<div style="text-align:center">
<h1>
Welcome to SuperHero!
</h1>
</div>

<app-page1></app-page1>

请帮忙 !!

最佳答案

AppComponent.html需要具有<router-outlet></router-outlet>指令:

<div style="text-align:center">
<h1>
Welcome to SuperHero!
</h1>
</div>

<-- The view is injected here -->
<router-outlet></router-outlet>

关于angular2-routing - Angular 4路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48146268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com