简体   繁体   中英

how to share data between two component using Event Emitter?

Could you please suggest how to add item in list when something enter in input field and then enter press.But these are different component .I want to share input field value to different component using @Input ,@Output ,EventEmitter.

I make one component . <todo></todo >

here is ts file

import { Page,NavController,Modal } from 'ionic-angular/index';
import { Component, Input, Output, EventEmitter} from 'angular2/core';



@Component({
  selector:'todo'
  templateUrl:"addtodo.html",
})
export class AddToDO{

constructor() {

    }
    addItem(v){
     alert(v.value)
    }
}

here is my html

<label class="item item-input">
<span class="input-label" >Add Todo</span>
  <input type="text" #todo placeholder="Add todo" (keyup.enter)="addItem(todo)">
</label>

I want to add item list when enter is press .so need to share data between component

http://plnkr.co/edit/N6aXDZXUr99MC6w77H6d?p=preview

I would leverage an @Output in your AddToDO component to trigger that an element was added. So you can catch it from the parent component and add the corresponding data in the list.

@Component({
  selector:'todo'
  templateUrl:"addtodo.html",
})
export class AddToDO{
  @Output()
  todoAdded:EventEmitter = new EventEmitter();

  constructor() {

  }

  addItem(v){
    alert(v.value)
    this.todoAdded.emit(v);
  }
}

and in the parent component template:

<todo (todoAdded)="addTodoInList($event)"></todo>

Here is the content of the addTodoInList method:

addTodoInList(todo) {
  this.Todo.push(todo);
}

See this plunkr: http://plnkr.co/edit/mQtQIXIJwMfJSfNVHvac?p=preview .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM