【问题标题】:How can I receive output from another Angular component?我如何接收来自另一个 Angular 组件的输出?
【发布时间】:2023-02-06 22:55:58
【问题描述】:

观看了角度教程,只是按照步骤操作,但现在我正在为@Output 苦苦挣扎。我无法从我的主组件中的另一个组件接收值。

我尝试将 Output 与 EventEmitter 一起使用,但不知何故它不起作用。

主页组件

<mat-drawer-container [autosize]="true" class="min-h-full max-w-7xl mx-auto">
  <mat-drawer mode="side" opened class="p-6">
    <app-filters (showCategory)="onShowCategory($event)"></app-filters>
  </mat-drawer>
  <mat-drawer-content class="p-6"
    ><app-products-header (columnsCountChange)="onColumnsCountChange($event)">{{
      category
    }}</app-products-header></mat-drawer-content
  >
</mat-drawer-container>

家庭组件 TS

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: `home.component.html`,
})
export class HomeComponent {
  cols = 3;
  category: string | undefined;
  onColumnsCountChange(colsNum: number): void {
    this.cols = colsNum;
  }

  onShowCategory(newCategory: string): void {
    this.category = newCategory;
  }
}

<mat-expansion-panel *ngIf="categories">
  <mat-expansion-panel-header>
    <mat-panel-title>CATEGORIES</mat-panel-title>
  </mat-expansion-panel-header>
  <mat-selection-list [multiple]="false">
    <mat-list-option *ngFor="let category of categories" [value]="category"
      ><button (click)="onShowCategory(category)">
        {{ category }}
      </button></mat-list-option
    >
  </mat-selection-list>
</mat-expansion-panel>

类别过滤器 TS

@Component({
  selector: 'app-filters',
  templateUrl: 'filters.component.html',
})
export class FiltersComponent {
  @Output() showCategory = new EventEmitter<string>();
  categories = ['shoes', 'sports'];

  onShowCategory(category: string): void {
    this.showCategory.emit(category);
  }
}

【问题讨论】:

  • 您遇到了什么样的错误,请检查您的控制台并与我们分享错误消息
  • 我没有收到任何错误。它只是没有显示价值... youtu.be/Kbauf9IgsC4?t=3971 但对他来说它正在显示...
  • 在下面检查我的答案

标签: javascript angular


【解决方案1】:

在这里,您将数据从父组件(Home Component)发送到子组件(Category Filter),因此您应该使用@input 装饰器而不是@output。查看这篇文章https://angular.io/guide/inputs-outputs

@Component({
  selector: 'app-filters',
  templateUrl: 'filters.component.html',
})
export class FiltersComponent {
  @Input() showCategory = new EventEmitter<string>();
  categories = ['shoes', 'sports'];

  onShowCategory(category: string): void {
    this.showCategory.emit(category);
  }
}

【讨论】:

  • 您确定我正在从父母发送给孩子吗?我想我是从孩子那里发送的...并且在视频中肯定使用了@Output并且它正在工作
猜你喜欢
  • 2019-03-10
  • 2022-01-15
  • 2019-09-09
  • 2023-01-12
  • 1970-01-01
  • 2020-01-28
  • 2018-12-29
  • 2019-11-19
  • 2012-08-07
相关资源
最近更新 更多