2016-07-28 90 views
5

我在Angular2中尋找AngularJS ISolated(= operation)作用域的類似功能。

我想更改子組件中的父組件值,以便我不需要使用任何EventEmitter。

以下是我的代碼片段。
如何在angular2中更新父組件的父組件

<component-1> 
<div *ngFor="let row of listArray" > 
    <component-2 [inputData]="row.inputData" (outputEvent)= "onComponentChange($event)"> </component-2> 
</div> 
<component-2 [inputData]="inputData2" (outputEvent)= "onComponentChange($event)"> </component-2> 
<component-2 [inputData]="inputData3" (outputEvent)= "onComponentChange($event)"> </component-2> 
<component-2 [inputData]="inputData4" (outputEvent)= "onComponentChange($event)"> </component-2> 

@Component 
component-1{ 
    onComponentChange(newValue){ 
     //where to keep the new value 
     //this.inputData2/inputData3/inputData4/listArray[i].inputData ??????????? 
    } 
} 


@Component 
component-2{ 
    @Input() inputData:string; 
    @Output() outputEvent:EventEmitter<string>; 
    changeComponentValue(newValue){ 
     this.outputEvent(newValue); 
    } 
} 

我將在部件-2變更[inputData]的值,即應在組件1反映。
在現有的@Output eventEmitter中,我無法找到要更改的元素值。

+0

你想改變的價值?或者只是想知道你正在處理哪個元素? – micronyks

回答

6

這裏我向您展示瞭如何識別您正在處理的元素的索引以及如何爲正在處理的元素分配新值。

一個新值賦給row.inputData我負責的雙向數據與@input XXX結合;和@Output xxxChange語法。

確定您正在處理的元素的索引我剛剛使用了新的@output API。

冷靜地觀察這段代碼。

@Component({ 
    selector: 'my-app', 
    directives:[ChildComponent], 
    template:`<h1>My First Angular 2 App</h1> 
    <div *ngFor="let row of listArray" > 
    {{row.inputData}} 
    <component-2 [(inputData)]="row.inputData" (outputEvent)= "onComponentChange($event)"> </component-2> 
    </div> 
    ` 
}) 
export class AppComponent { 
title="Angular1"; 

listArray=[{inputData:"micronyks"},{inputData:"micronyks1"},{inputData:"micronyks3"}]; 

onComponentChange(value){ 
    console.log(value); 
    this.listArray.forEach((item,index)=>{ 
    if(item.inputData==value){ 
     console.log(index); 
    } 
    }) 
} 
} 

組件2

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

@Component({ 
    selector: 'component-2', 
    template:`<button (click)="changeComponentValue(inputData)">Click-{{inputData}}</button>` 
}) 
export class ChildComponent { 
    @Input() inputData; 
    @Output() outputEvent:EventEmitter<string>=new EventEmitter(); 
    @Output() inputDataChange=new EventEmitter(); 

    changeComponentValue(value){ 
     this.outputEvent.emit(value); //<---this will identify element index you are dealing with 
     this.inputDataChange.emit("Angular2"); //<----new value will be assinged to an element that you are dealing with 
    } 
} 

工作演示:https://plnkr.co/edit/SqrfhtZZlSIsQE0Ko0oC?p=preview

+0

非常感謝。這是我正在尋找的,我不需要得到行索引。只要它正在改變對我來說足夠的父母價值。我沒有聽說inputDataChange是如何工作的,任何方式我都會嘗試找到它。非常感謝您的參與。 –

+0

哦,太棒了。很高興知道你喜歡它。 – micronyks

相關問題