angular - angular2 generate list of buttons with click binding to components -
i have component generates list of buttons, , i'd bind click event display child component. have working single button/component, uses local variable has same value each button, doesn't work correctly:
<div *ngfor="let key of keys"> <button (click)="child.togglecollapse()"> display </button> <app-child-component #child [key]="key"></app-child-component> </div> so problem 'child' same value each button/child, , opens last child. idea somehow bind 'key' '#child' id.
what's correct way in angular2?
in application use solution similar following solution:
in parent component can hold expanded child id (-1 if no child expanded). can pass unique child id , expanded child id each child using @input (passing data parent child). each child knows id , knows if expanded or not (index === expandedindex). if want expand/collapse child (e.g. after child's button click) can send event using @output , eventemitter (passing data child parent) parent change expanded child id.
parent component
import { component } '@angular/core'; @component({ selector: 'app-root', template: ` <div *ngfor="let key of keys; let index = index"> <app-child [key]="key" [index]="index" [expandedindex]="expandedindex" (changeindex)="onchangeindex($event)"></app-child> </div> ` }) export class appcomponent { keys: string[] = ['a', 'b', 'c']; expandedindex: number = -1; onchangeindex(index: number) { if (this.expandedindex === index) { this.expandedindex = -1; } else { this.expandedindex = index; } } } child component
import { component, oninit, input, output, eventemitter } '@angular/core'; @component({ selector: 'app-child', template: ` <div style="margin-top: 20px; border: 1px solid #ddd"> <button (click)="onexpand()">{{expandedindex !== index ? 'expand' : 'collapse'}}</button> <div *ngif="expandedindex === index"> <p>{{key}}</p> </div> </div> ` }) export class childcomponent implements oninit { @input() key: string; @input() index: number; @input() expandedindex: number; @output() changeindex = new eventemitter<number>(); constructor() { } ngoninit() { } onexpand() { this.changeindex.emit(this.index); } }
Comments
Post a Comment