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

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

Pass menu item name to routing component in Angular 12

问题

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

#app.component.html

<div class="root">
    <div class="side-bar">
        <app-side-bar></app-side-bar>
    </div>
    <div class="main-content">
        <router-outlet></router-outlet>
    </div>
</div>
# app-routing.module.ts

const routes: Routes = [

  {
    path: '',
    component: WelcomeComponent,
  },
  {
    path: 'category/:id',
    component: MainContentComponent,
  },
]

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

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

# side-bar.component.html
<aside>
#HTML stuff
  <main class="container" *ngFor="let item of items">
    <div class="trilha" [routerLink]="['/category/'+ item.id]">
      <span class="item-name">{{ item.title }}</span>
    </div>
  </main>
</aside>

@Component({
  selector: "app-side-bar",
  templateUrl: "./side-bar.component.html",
  styleUrls: ["./side-bar.component.css"],
})
export class SideBArComponent implements OnInit {
  categories: any;

  constructor(private categoryService: CategoryService) {}

  ngOnInit(): void {
    this.categoryService.findAll().subscribe((data : Category[]) => {
      this.categories = data;
    });
  }
}

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

# main-content.component.html


<app-header [Title]= "CATEGORY NAME"></app-header>

<div class="content">
    <app-category-content></app-category-content>
</div>
# main-content.component.ts

@Component({
  selector: "app-main-content",
  templateUrl: "./main-content.component.html",
  styleUrls: ["./main-content.component.css"],
})
export class MainContentComponent implements OnInit {
  categoryId: number = 0;


  constructor(
    private service: CategoryService,
    private activatedRoute: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.categoryId = this.activatedRoute.snapshot.params["id"];
  }

如何将路由组件的名称传递给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.

#app.component.html

&lt;div class=&quot;root&quot;&gt;
    &lt;div class=&quot;side-bar&quot;&gt;
        &lt;app-side-bar&gt;&lt;/app-side-bar&gt;
    &lt;/div&gt;
    &lt;div class=&quot;main-content&quot;&gt;
        &lt;router-outlet&gt;&lt;/router-outlet&gt;
    &lt;/div&gt;
&lt;/div&gt;
# app-routing.module.ts

const routes: Routes = [

  {
    path: &#39;&#39;,
    component: WelcomeComponent,
  },
  {
    path: &#39;category/:id&#39;,
    component: MainContentComponent,
  },
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
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.

# side-bar.component.html
&lt;aside&gt;
#HTML stuff
  &lt;main class=&quot;container&quot; *ngFor=&quot;let item of items&quot;&gt;
    &lt;div class=&quot;trilha&quot; [routerLink]=&quot;[&#39;/category/&#39;+ item.id]&quot;&gt;
      &lt;span class=&quot;item-name&quot;&gt;{{ item.title }}&lt;/span&gt;
    &lt;/div&gt;
  &lt;/main&gt;
&lt;/aside&gt;

@Component({
  selector: &quot;app-side-bar&quot;,
  templateUrl: &quot;./side-bar.component.html&quot;,
  styleUrls: [&quot;./side-bar.component.css&quot;],
})
export class SideBArComponent implements OnInit {
  categories: any;

  constructor(private categoryService: CategoryService) {}

  ngOnInit(): void {
    this.categoryService.findAll().subscribe((data : Category[]) =&gt; {
      this.categories = data;
    });
  }
}

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

# main-content.component.html


&lt;app-header [Title]= &quot;CATEGORY NAME&quot;&gt;&lt;/app-header&gt;

&lt;div class=&quot;content&quot;&gt;
    &lt;app-category-content&gt;&lt;/app-category-content&gt;
&lt;/div&gt;
# main-content.component.ts

@Component({
  selector: &quot;app-main-content&quot;,
  templateUrl: &quot;./main-content.component.html&quot;,
  styleUrls: [&quot;./main-content.component.css&quot;],
})
export class MainContentComponent implements OnInit {
  categoryId: number = 0;


  constructor(
    private service: CategoryService,
    private activatedRoute: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.categoryId = this.activatedRoute.snapshot.params[&quot;id&quot;];
  }

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文件,内容如下:

import { Subject } from "rxjs";

export class AppStore {
  static categoryName$ = new Subject<string>();
}

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

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

在你的头部组件中:

sub$ = new Subscription();

ngOnInit() {
  this.subs$.add(
    AppStore.categoryName$.subscribe(name => {
      this.title = name;
    })
  );
}

ngOnDestroy() {
  this.sub$.unsubscribe();
}

所以基本上,在这里我们以一种响应式的方式在组件之间共享数据。如果你使用的是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:

import { Subject } from &quot;rxjs&quot;;

export class AppStore {
  static categoryName$ = new Subject&lt;string&gt;();
}

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

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

In your header component:

sub$ = new Subscription();

ngOnInit() {
  this.subs$.add(
    AppStore.categoryName$.subscribe(name =&gt; {
      this.title = name;
    })
  );
}

ngOnDestroy() {
  this.sub$.unsubscribe();
}

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:

确定