-1

I have two independent components in my application nav.component and list.component. The main idea is to send from nav.component to list.component and in list.component add that value in array. I read that there are existing a lot of different ways how to achieve this. I tried EventEmitter but it seems that my approach is not working. Why? And what is proper way?

nav component

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

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);
  }
}
Liam
  • 27,717
  • 28
  • 128
  • 190
A191919
  • 3,422
  • 7
  • 49
  • 93
  • 7
    There is a whole page in the documentation about interaction between component. https://angular.io/guide/component-interaction – broodjetom Sep 20 '19 at 12:31

2 Answers2

0

You are not calling onAddItem anywhere in ListComponent, that's the main reason why it is not working.

The EventEmitter approach can be used for passing data between parent and child components, which also does not seem to be the case in your example.

You could try another approach such as using a service for passing the data.

LeBavarois
  • 938
  • 2
  • 11
  • 24
-1

As pointed out by @broodjetom, the documentation at angular.io/guide/component-interaction explains everything one needs to know about component interaction, with examples.

If you want to use event emitter though, and you are instantiating your list.component by using the selector, you will need to bind to a method in that component and handle the event (that contains the payload) in there.

For example, in your selector you could have:

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

and then handle the string payload contained in the event in your onAddItem method.

Hope that helps.

Wayne C
  • 83
  • 2
  • 9