【问题标题】:Angular 8 send data between two components [duplicate]Angular 8在两个组件之间发送数据[重复]
【发布时间】:2020-01-21 12:18:40
【问题描述】:

我的应用程序nav.componentlist.component 中有两个独立的组件。主要思想是从nav.component 发送到list.component 并在list.component 中将该值添加到数组中。我读到有很多不同的方法可以实现这一目标。我尝试了 EventEmitter 但似乎我的方法不起作用。为什么?什么是正确的方法?

导航组件

nav.component.html:

<mat-form-field class="example-full-width">
    <input matInput placeholder="Add" [(ngModel)]="value" >
</mat-form-field>

<div class="example-button-row">
    <button mat-stroked-button (click)="sendMessage()">Add</button>
</div>

nav.component.ts:

import { Component, OnInit ,EventEmitter, Input, Output} from '@angular/core';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {

  public value:string;

  @Output() onAddItem = new EventEmitter<string>();

  constructor() { }

  ngOnInit() {
  }

  sendMessage() {
    this.onAddItem.emit(this.value);
  }
}

列表组件

list.component.html

<mat-list role="list">
    <mat-list-item role="listitem" *ngFor="let product of Products">{{product}}</mat-list-item>
</mat-list>

list.component.ts

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

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {

  public Products:string[] = ["one","two","Three","Four","Five"];

  constructor() { 
  }

  ngOnInit() {
  }

  onAddItem(item:string)  {
    this.Products.push(item);
  }
}

【问题讨论】:

标签: angular


【解决方案1】:

你没有在 ListComponent 的任何地方调用onAddItem,这是它不起作用的主要原因。

EventEmitter 方法可用于在父组件和子组件之间传递数据,在您的示例中似乎也不是这种情况。

您可以尝试另一种方法,例如使用服务来传递数据。

【讨论】:

    【解决方案2】:

    正如@broodjetom 所指出的,位于 angular.io/guide/component-interaction 的文档通过示例解释了人们需要了解的有关组件交互的所有信息。

    如果你想使用事件发射器,并且你正在使用选择器实例化你的list.component,你将需要绑定到该组件中的一个方法并在那里处理事件(包含有效负载)。

    例如,在您的选择器中,您可以:

    <list-component-selector (onAddItem)='onAddItem($event)'></list-component-selector>
    

    然后在您的onAddItem 方法中处理事件中包含的字符串有效负载。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2017-10-31
      • 2021-02-27
      • 2018-02-22
      • 2020-10-10
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多