要在Angular 2+中通过Router重定向到另一个组件的HTML,你可以使用Angular的路由导航功能。
首先,确保你已经正确设置了路由。在你的app.module.ts文件中,确保你已经导入了RouterModule,并在imports数组中添加了RouterModule.forRoot(routes)。其中routes是一个包含你的路由配置的数组。
下面是一个示例的路由配置:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { OtherComponent } from './other.component';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'other', component: OtherComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
然后,在你想要重定向的组件中,你可以使用Router的navigate方法来进行重定向。在组件的构造函数中注入Router,并在需要重定向的地方调用navigate方法。
下面是一个示例的组件代码:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
template: `
Welcome to the Home Component!
`,
})
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
}
redirectToOther() {
this.router.navigate(['/other']);
}
}
在上面的示例中,当用户点击按钮时,redirectToOther方法会使用Router来导航到'other'路径,从而重定向到OtherComponent的HTML。
确保你的组件正确导入了Router,并且你已经在应用的主模块中引入了AppRoutingModule。
希望这能帮助到你解决问题!