簡體   English   中英

如何從angular2中的子組件更新父組件

[英]how to update parent component from child component in angular2

我在Angular2中尋找AngularJS ISolated(= operation)范圍的類似功能。

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

以下是我的代碼片段。

<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中,我無法找到哪個元素值已更改。

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

row.inputData分配一個新值我正在處理與@Input xxx的 TWO-WAY數據綁定; @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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM