angular - how to update parent component from child component in angular2 -
i looking angularjs isolated(= operation) scope similar feature in angular2.
change parent component value in child component, don't need use eventemitters.
following code snippet.
<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 keep new value //this.inputdata2/inputdata3/inputdata4/listarray[i].inputdata ??????????? } } @component component-2{ @input() inputdata:string; @output() outputevent:eventemitter<string>; changecomponentvalue(newvalue){ this.outputevent(newvalue); } }
i change [inputdata] value in component-2, should reflect in component-1.
in existing @output eventemitter, unable find element value got changed.
here i'm showing how identify index of element dealing , how assign new value element dealing with.
to assign new value row.inputdata i'm dealing two-way data binding @input xxx; , @output xxxchange syntax.
to identify index of element dealing i'm using new @output api.
observe code calmly.
@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); } }) } }
component-2
import { component, input,output,eventemitter } '@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 identify element index dealing this.inputdatachange.emit("angular2"); //<----new value assinged element dealing } }
working demo : https://plnkr.co/edit/sqrfhtzzlsisqe0ko0oc?p=preview
Comments
Post a Comment