javascript - How to have component interact with nested dialog component in Angular 2? -
i have generic component. component has n buttons, n can set parent. parent component can have multiple instances of generic component. when button clicked on generic component, need notify parent component button has been pressed, , way identify button has been pressed. need have parent component able call function on nested component. here's rough example of i'm looking do:
@component({ selector: 'parent-component', ... }) export class parentcomponent{ public ongenericcomponentbuttonpress(someid){ if (someid === "foo"){ genericcomponentinstance.closecomponent(); }else{ dootherthing(); } } } @component({ selector: 'generic-component', ... }) export class genericcomponent{ public closecomponent(){} }
i need way communicate , forth this. assuming parent component can have multiple instances of genericcomponent, possible?
you need 2 communication forms:
- child parent
- parent child
child parent
communicating child parent can done adding eventemmiter on child , subscribing event on parent. calling parent done calling emit
on eventemitter
child component code:
import { component, eventemitter, output } '@angular/core'; @component({ selector: 'my-child', template: '<h2>{{mytext}}</h2><button (click)="onclick()">do something</button>' }) export class childcomponent { private mytext = "child component"; @output() clicked: eventemitter<any> = new eventemitter(); public onclick() { this.clicked.emit(); } }
parent component code:
import { component} '@angular/core'; import { childcomponent } "./child.component"; @component({ selector: 'my-app', template: `<h1>parent component</h1> <my-child (clicked)="dosomething()"></my-child>`, directives: [childcomponent] }) export class appcomponent { public dosomething() { something... } }
parent child
to call child component first need reference component, done using viewchildren if have multiple components of same type.
parent component code:
import { component, viewchildren, querylist} '@angular/core'; import { childcomponent } "./child.component"; @component({ selector: 'my-app', template: `<h1>parent component</h1> <my-child></my-child>`, directives: [childcomponent] }) export class appcomponent { @viewchildren(childcomponent) children:querylist<childcomponent>; public callchild(){ this.children.toarray()[0].dosomething(); } }
example in plnkr
note: there other ways communicate between components such using common service.
Comments
Post a Comment