Angular 7 从一个组件导航到另一个组件
创始人
2024-10-16 18:00:34
0

要从一个Angular 7组件导航到另一个组件,你可以使用Angular的内置路由器。以下是一个完整的示例,展示了如何实现组件之间的导航。

首先,确保你已经正确设置了路由器并定义了所有需要导航的组件。你可以在app.module.ts文件中设置路由器,并在app-routing.module.ts文件中定义路由。

在app.module.ts文件中设置路由器:

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

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { OtherComponent } from './other/other.component';

const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'other', component: OtherComponent },
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    OtherComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

在app-routing.module.ts文件中定义路由:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { OtherComponent } from './other/other.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'other', component: OtherComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' } // 默认导航到home组件
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

现在,你可以在组件中使用路由器导航到其他组件。在需要触发导航的组件中,导入Router类,并使用navigate方法导航到目标组件。

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

@Component({
  selector: 'app-home',
  template: `
    

Welcome to Home Component!

`, styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { } goToOther() { this.router.navigate(['/other']); } }

在上面的示例中,我们在HomeComponent中使用了一个按钮,并通过调用goToOther方法来触发导航到OtherComponent。在goToOther方法中,我们使用router.navigate方法,并传入目标组件的路径作为参数。

现在,当你点击Home组件中的按钮时,将会导航到Other组件。

相关内容

热门资讯

第二分钟辅助!wepokerp... 第二分钟辅助!wepokerplus脚本,hhpoker德州牛仔视频,机巧教程(有挂技术)1、全新机...
四分钟辅助!HH平台挂,pok... 四分钟辅助!HH平台挂,pokemmo修改器手机版,攻略教程(有挂存在)1、pokemmo修改器手机...
第2分钟辅助!wepoker底... 第2分钟辅助!wepoker底牌透视,aapoker怎么开辅助器,演示教程(有挂解惑)1、玩家可以在...
第2分钟辅助!wpk透视怎么安... 第2分钟辅助!wpk透视怎么安装,wepoker手机助手,手段教程(有挂教学)1、wpk透视怎么安装...
七分钟辅助!wepoker免费... 您好,wepoker免费脚本弱密码这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
第6分钟辅助!wejoker开... 第6分钟辅助!wejoker开挂,aa poker辅助,妙计教程(有挂细节)1、aa poker辅助...
6分钟辅助!德州透视脚本,hh... 6分钟辅助!德州透视脚本,hh poker软件,教程书教程(真的有挂)1、任何德州透视脚本透视是真的...
十分钟辅助!pokemmo手机... 十分钟辅助!pokemmo手机版脚本免费,wepoker祈福有用吗,手段教程(有挂方式)1、poke...
第2分钟辅助!wepoker免... 第2分钟辅助!wepoker免费脚本咨询,wepoker透视器免费,积累教程(有挂总结)wepoke...
第六分钟辅助!aapoker怎... 第六分钟辅助!aapoker怎么设置提高好牌几率,德普之星透视免费,法子教程(有挂猫腻)所有人都在同...