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);
}
}