将菜单项名称传递给Angular 12中的路由组件

huangapple go评论110阅读模式
英文:

Pass menu item name to routing component in Angular 12

问题

我是Angular的新手,我正在尝试创建一个应用程序,其中包含两个主要组件:侧边栏和主组件。

  1. #app.component.html
  2. <div class="root">
  3. <div class="side-bar">
  4. <app-side-bar></app-side-bar>
  5. </div>
  6. <div class="main-content">
  7. <router-outlet></router-outlet>
  8. </div>
  9. </div>
  1. # app-routing.module.ts
  2. const routes: Routes = [
  3. {
  4. path: '',
  5. component: WelcomeComponent,
  6. },
  7. {
  8. path: 'category/:id',
  9. component: MainContentComponent,
  10. },
  11. ]
  12. @NgModule({
  13. imports: [RouterModule.forRoot(routes)],
  14. exports: [RouterModule]
  15. })
  16. export class AppRoutingModule { }

在侧边栏组件中,我有一个动态列表,当用户点击一个项目时,相应的组件会显示在主组件中。

  1. # side-bar.component.html
  2. <aside>
  3. #HTML stuff
  4. <main class="container" *ngFor="let item of items">
  5. <div class="trilha" [routerLink]="['/category/'+ item.id]">
  6. <span class="item-name">{{ item.title }}</span>
  7. </div>
  8. </main>
  9. </aside>
  1. @Component({
  2. selector: "app-side-bar",
  3. templateUrl: "./side-bar.component.html",
  4. styleUrls: ["./side-bar.component.css"],
  5. })
  6. export class SideBArComponent implements OnInit {
  7. categories: any;
  8. constructor(private categoryService: CategoryService) {}
  9. ngOnInit(): void {
  10. this.categoryService.findAll().subscribe((data : Category[]) => {
  11. this.categories = data;
  12. });
  13. }
  14. }

在主组件中,我有一个标题子组件,应该显示在侧边栏中点击的选项的名称。

  1. # main-content.component.html
  2. <app-header [Title]= "CATEGORY NAME"></app-header>
  3. <div class="content">
  4. <app-category-content></app-category-content>
  5. </div>
  1. # main-content.component.ts
  2. @Component({
  3. selector: "app-main-content",
  4. templateUrl: "./main-content.component.html",
  5. styleUrls: ["./main-content.component.css"],
  6. })
  7. export class MainContentComponent implements OnInit {
  8. categoryId: number = 0;
  9. constructor(
  10. private service: CategoryService,
  11. private activatedRoute: ActivatedRoute
  12. ) {}
  13. ngOnInit(): void {
  14. this.categoryId = this.activatedRoute.snapshot.params["id"];
  15. }

如何将路由组件的名称传递给Header组件,以便在Header上显示它?

英文:

I am new to Angular and I'm trying to create an app that has two main components: a side bar and the main component.

  1. #app.component.html
  2. &lt;div class=&quot;root&quot;&gt;
  3. &lt;div class=&quot;side-bar&quot;&gt;
  4. &lt;app-side-bar&gt;&lt;/app-side-bar&gt;
  5. &lt;/div&gt;
  6. &lt;div class=&quot;main-content&quot;&gt;
  7. &lt;router-outlet&gt;&lt;/router-outlet&gt;
  8. &lt;/div&gt;
  9. &lt;/div&gt;
  1. # app-routing.module.ts
  2. const routes: Routes = [
  3. {
  4. path: &#39;&#39;,
  5. component: WelcomeComponent,
  6. },
  7. {
  8. path: &#39;category/:id&#39;,
  9. component: MainContentComponent,
  10. },
  11. ]
  12. @NgModule({
  13. imports: [RouterModule.forRoot(routes)],
  14. exports: [RouterModule]
  15. })
  16. export class AppRoutingModule { }

In the side bar component i have a dynamic list with and when the user clicks on a item the corresponding component is shown in the main component.

  1. # side-bar.component.html
  2. &lt;aside&gt;
  3. #HTML stuff
  4. &lt;main class=&quot;container&quot; *ngFor=&quot;let item of items&quot;&gt;
  5. &lt;div class=&quot;trilha&quot; [routerLink]=&quot;[&#39;/category/&#39;+ item.id]&quot;&gt;
  6. &lt;span class=&quot;item-name&quot;&gt;{{ item.title }}&lt;/span&gt;
  7. &lt;/div&gt;
  8. &lt;/main&gt;
  9. &lt;/aside&gt;
  1. @Component({
  2. selector: &quot;app-side-bar&quot;,
  3. templateUrl: &quot;./side-bar.component.html&quot;,
  4. styleUrls: [&quot;./side-bar.component.css&quot;],
  5. })
  6. export class SideBArComponent implements OnInit {
  7. categories: any;
  8. constructor(private categoryService: CategoryService) {}
  9. ngOnInit(): void {
  10. this.categoryService.findAll().subscribe((data : Category[]) =&gt; {
  11. this.categories = data;
  12. });
  13. }
  14. }

In the main component I have a header subcomponent that should display the name of the option clicked in the side bar.

  1. # main-content.component.html
  2. &lt;app-header [Title]= &quot;CATEGORY NAME&quot;&gt;&lt;/app-header&gt;
  3. &lt;div class=&quot;content&quot;&gt;
  4. &lt;app-category-content&gt;&lt;/app-category-content&gt;
  5. &lt;/div&gt;
  1. # main-content.component.ts
  2. @Component({
  3. selector: &quot;app-main-content&quot;,
  4. templateUrl: &quot;./main-content.component.html&quot;,
  5. styleUrls: [&quot;./main-content.component.css&quot;],
  6. })
  7. export class MainContentComponent implements OnInit {
  8. categoryId: number = 0;
  9. constructor(
  10. private service: CategoryService,
  11. private activatedRoute: ActivatedRoute
  12. ) {}
  13. ngOnInit(): void {
  14. this.categoryId = this.activatedRoute.snapshot.params[&quot;id&quot;];
  15. }

How do I pass the name for the routed component so I can display it on the Header?

答案1

得分: 1

在组件之间共享数据有两种方式:

  1. 通过Redux
  2. 通过RxJs的Subject/BehaviorSubject

我将给出一种通过RxJs的解决方案。

在src/app中创建一个app-store.ts文件,内容如下:

  1. import { Subject } from "rxjs";
  2. export class AppStore {
  3. static categoryName$ = new Subject<string>();
  4. }

现在在你的组件中使用这个AppStore来发出数据,例如:

  1. AppStore.categoryName$.next("我的动态类别名称");

在你的头部组件中:

  1. sub$ = new Subscription();
  2. ngOnInit() {
  3. this.subs$.add(
  4. AppStore.categoryName$.subscribe(name => {
  5. this.title = name;
  6. })
  7. );
  8. }
  9. ngOnDestroy() {
  10. this.sub$.unsubscribe();
  11. }

所以基本上,在这里我们以一种响应式的方式在组件之间共享数据。如果你使用的是Angular v16,你甚至可以使用Angular v16中引入的signal。希望这能帮助解决这个问题以及未来与组件之间共享数据相关的问题。

英文:

There are two ways of sharing data between components:

  1. Via Redux
  2. Via RxJs Subject/BehaviorSubject
    I'm going to give a solution via RxJs.

Create a app-store.ts in src/app with following content:

  1. import { Subject } from &quot;rxjs&quot;;
  2. export class AppStore {
  3. static categoryName$ = new Subject&lt;string&gt;();
  4. }

Now use this AppStore in your component to emit a data like this:

  1. AppStore.categoryName$.next(&quot;my dynamic category name&quot;);

In your header component:

  1. sub$ = new Subscription();
  2. ngOnInit() {
  3. this.subs$.add(
  4. AppStore.categoryName$.subscribe(name =&gt; {
  5. this.title = name;
  6. })
  7. );
  8. }
  9. ngOnDestroy() {
  10. this.sub$.unsubscribe();
  11. }

So basically here, we are sharing data between components in a reactive way. Even you can use signal which introduced in Angular v16 if you are using Angular v16.
I hope it will help to solve this problem and future problems related to share data between components.

huangapple
  • 本文由 发表于 2023年8月9日 03:13:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定