【问题标题】:passe data from component to another using input & output使用输入和输出将数据从组件传递到另一个组件
【发布时间】:2021-07-28 08:13:37
【问题描述】:

我尝试将数据传递给 msg 组件以过滤组件,并且两个组件都注入到主组件中,我尝试了几种组合但仍然无法做到。

我不知道@input 或@output 用什么?

ma​​in.component.html

<app-msg></app-msg> // pass data from this component to fitler component
<app-filter (filterMSg)='msg'></app-filter>

filter.component.ts

filterMSg:string = '';

msg.component.ts

msg:string = 'text from msg component';

【问题讨论】:

  • @Input@Output 用于在另一个选择器中使用一个选择器的相关组件。例如。在您的情况下,您可以将其用于数据共享 b/n Main 组件以及 Msg 或 Filter 组件。对于不相关的组件,您可以查看单例服务。见here

标签: angular typescript


【解决方案1】:

如果我猜对了,您想将消息从您的 msg 组件传递到您的过滤器组件吗?

如果是这种情况,你需要:

  1. 从您的 msg 组件中获取数据,通过 @Output() 在您的主组件中。
  2. 通过@Input() 将主组件中接收到的数据发送到您的过滤器组件

第 1 步

在你的 msg.component.ts 中:

export class MsgComponent {
  @Output() messageEmitter: EventListener<string> = new EventListener<string>();

  public emitMessage(message: string): void {
    messageEmitter.emit(message);
  }
}

在这里,您创建一个 EventListener,当您希望将其传递给 main 时,您将使用方法 emitMessage() 触发它。

在你的 main.component.ts 中:

export MainComponent {
  public message: string = '';

  public getMessage(message: string): void {
    this.message = message;
  }
}

您在 main 中创建一个方法来获取 @Output() 的值

在你的 main.component.html 中:

  <app-msg (messageEmitter)=getMessage($event)></app-msg>

您使用 main.component.ts 中定义的方法在子级中触发 @Output() 时获取消息。

第二步

在 filter.component.ts 中:

export class FilterComponent {
  @Input() message: string;
}

您创建 一个 @Input() 将获取父级发送的数据(主要组件)。

在 main.component.html 中:

<app-filter [message]=message></app-filter>

将消息从主组件发送(写在“=”符号之后)到子属性消息(括号之间)。

【讨论】:

    【解决方案2】:

    有点不清楚你的要求是什么。

    子组件向其父组件发送数据的简单示例可能是:

    export class ItemOutputComponent {
    
      @Output() newItemEvent = new EventEmitter<string>();
    
      addNewItem(value: string) {
        this.newItemEvent.emit(value);
      }
    }
    

    这是一个从父级获取数据的组件的简单示例。

    import { Component, Input } from '@angular/core'; // First, import Input
    export class ItemDetailComponent {
      @Input() item = ''; // decorate the property with @Input()
    }
    

    请查看 inputs-outputs 的 angular 文档!

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 2019-12-26
      • 2017-03-21
      • 1970-01-01
      • 2021-12-30
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多