2016-05-24 28 views
0

請問如何在列表中添加項時,如果在輸入字段中輸入東西,然後按enter press.But這些是不同的組件。我想要使用@Input,@ Output,EventEmitter將輸入字段值共享到不同的組件。如何使用事件發射器在兩個組件之間共享數據?

我做一個組件。 <todo></todo>

這裏TS文件

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

這裏是我的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> 

我想進入的時候添加項目列表是按。所以需要組件

之間共享數據

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

回答

1

我wou ld利用AddToDO組件中的@Output觸發添加元素。所以你可以從父組件中捕獲它並在列表中添加相應的數據。

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

    constructor() { 

    } 

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

並在父組件的模板:

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

這裏是addTodoInList方法的內容:

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

見本plunkr:http://plnkr.co/edit/mQtQIXIJwMfJSfNVHvac?p=preview

相關問題