在Angular 7中,可以使用子路由来替换父组件。以下是一个示例解决方法:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Parent Component
`,
})
export class ParentComponent { }
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Child Component
`,
})
export class ChildComponent {
replaceParent() {
// 在子组件中导航到新的组件
this.router.navigate(['/new-component']);
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-new',
template: `
New Component
`,
})
export class NewComponent {
constructor(private location: Location) { }
goBack() {
// 在新组件中返回到父组件
this.location.back();
}
}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
import { NewComponent } from './new.component';
const routes: Routes = [
{
path: '',
component: ParentComponent,
children: [
{ path: 'child', component: ChildComponent },
{ path: 'new-component', component: NewComponent },
],
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
import { NewComponent } from './new.component';
@NgModule({
declarations: [
AppComponent,
ParentComponent,
ChildComponent,
NewComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
在上述示例中,当点击子组件中的按钮时,将导航到新组件。然后,当在新组件中点击“返回”按钮时,将返回到父组件。
请确保在根模块(app.module.ts)中导入和添加所有组件,并在路由器模块(app-routing.module.ts)中定义所有路由。
上一篇:Angular 7 自动刷新令牌
下一篇:Angular 7 组件