【发布时间】:2018-05-25 22:46:24
【问题描述】:
如何在 Angular 中的路由事件中相对于其他组件更改一个组件中的数据?
例如如果我有三个组件:"nav.component"、"about.component" 和 "service.component"。
所以当我在我的应用程序中的about 和service 页面之间切换时,我想在"nav.component" 中显示不同的文本。
我的"app.router.ts" 文件:
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServiceComponent } from './service/service.component';
export const router: Routes = [
{ path: '', redirectTo: 'about', pathMatch: 'full' },
{ path: 'about', component: AboutComponent },
{ path: 'service', component: ServiceComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
在这些页面之间切换时,我不想在导航栏中只显示页面名称文本,这将是每个组件的自定义文本。
此外,由于可维护性和可扩展性,我想将此数据/文本直接存储在 "about.component.ts" 和 "service.component.ts" 中,但不存储在 "app.router.ts" 中。
有可能吗?
U.P.D.
这是我的"app.component.html" 文件:
<div class="container">
<!-- Nav Bar (text changes here) -->
<app-nav></app-nav>
<!-- Pages (components which are included in app.router.ts) -->
<router-outlet></router-outlet>
</div>
例如这是"about.component.ts" 文件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.scss']
})
export class AboutComponent implements OnInit {
const text_for_nav_bar = "This is my new About page."; // <-- text that should be displayed in nav component for this page on router event.
constructor() { }
ngOnInit() {
}
}
【问题讨论】:
-
您的要求不明确。什么是导航组件?您的应用程序结构如何?自定义文本是什么意思?你想在哪里显示它?回答您的问题需要所有这些信息。
-
你可以通过路由更改事件做到这一点:stackoverflow.com/questions/33520043/…
-
@VinodBhavnani,我已经更新了我的帖子,希望这会有所帮助。我想为每个组件存储自定义文本字符串,此字符串应显示在
nav组件中,具体取决于路由器。
标签: javascript angular components