2017-01-18 2 views
0

У меня есть компонент stockTakeDetail, который используется в тэге тэга в виде строки таблицы ... Я использую компонент с селектором атрибутов [componentName] в строке таблицы, компонент stockTakeDetail испускает значение removeItem, когда нажимается кнопка, и я не уверен, как зарегистрировать это событие с его родительским компонентом ... Обычно я бы сделать что-то вроде этого:Angular2: Как использовать атрибут (событие) в родительском представлении, когда дочерний компонент добавлен с помощью селектора атрибутов

<stockTakeDetail (removeItem)="removeItem($event)"></stockTakeDetail> 

В моем родительском компоненте у меня есть следующий код:

<tr *ngFor="let stockTakeDetailItem of stockTakeDetailList" [stockTakeDetail]="stockTakeDetailItem"></tr> 

Любая идея, как я могу добавить событие в родительский html tr? Или есть способ получить событие непосредственно в контроллере родителя?

мой код:

stock-take-detail.html: 

<td>{{stockTakeDetail.ProductDetail_Name</td> 
<td>{{stockTakeDetail.Qty}}</td> 
<td><button class="btn btn-xs" (click)="removeCaptureItem({{stockTakeDetail.IDKey}})"><span class="glyphicon glyphicon-trash"></span></button></td> 

stock-take-detail.ts: 

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

import { StockTakeDetailModel } from '../../models/stock-take-detail.model'; 

@Component({ 
    selector: '[stockTakeDetail]', 
    templateUrl: './stock-take-detail.component.html', 
    styleUrls: ['./stock-take-detail.component.css'] 
}) 
export class StockTakeDetailComponent implements OnInit { 
    @Input() stockTakeDetail: StockTakeDetailModel; 
    @Output() removeItem = new EventEmitter<string>(); 


    removeCaptureItem(iDKey: string) {  
     this.removeItem.emit() 
    } 


    constructor() { } 

    ngOnInit() { 
    } 

} 


table from stock-take.html: 

<table class="table table-hover"> 
      <thead> 
       <tr> 
        <th>Desc</th> 
        <th>Qty</th> 
        <th>Action</th> 
       </tr>  
     </thead> 
     <tbody> 
      <!--<tr *ngFor="let stockTakeDetailItem of stockTakeDetailList" [stockTakeDeTail]="stockTakeDetailItem"></tr>--> 
     </tbody> 
     </table> 
+0

вы можете использовать Event Emitter и излучать этот канун nt, так что родитель может использовать его –

+0

@Yashveer Singh Я делаю это ... думаю, вы можете быть недоразумением – user2094257

+0

ok можете ли вы поделиться своим компонентом.ts для получения подробной информации о компоненте и шаблоне родителя, пожалуйста, –

ответ

0

Это может помочь; у родителя есть EventEmitter, вы передаете его детям в ngFor. Любой из детей, которые используют этот эмиттер для испускания события, все остальные дети услышат его, если хотите (они просто подписываются), и родитель услышит любой компонент, который использует его излучатель, чтобы испустить событие (например, детей), если вы подписываетесь. Очень просто, отлично работает.

<ul> 
    <li *ngFor="let btn of buttons"> 
    // Bind the parent's broadcast listener, to the child Input. 
    <my-child [broadcastListener]="broadcasterParent"> 
    </my-child> 
    </li> 
</ul> 

Родитель:

import { Component, EventEmitter } from '@angular/core'; 
    ... 
    constructor ) { 
    // this is the instance given to the child as Input 
    this.broadcasterParent = new EventEmitter (); 
    // Note if you want the parent to hear the event, 
    // subscribe to the event emitter, just like the children do. 
    this.broadcastListener.subscribe((b) => this.onBroadcast (b)); 

} 

onBroadcast (evt) { 
    ... you will hear when the child emits an event using the emitter 
} 

ребенка:

import { Component } from '@angular/core'; 
... 
constructor () { 
    // This is almost certainly better used in OnInit. 
    // It is how the child subscribes to the parent's event emitter. 
    // You only need to do this if you want to hear events. 
    this.broadcastListener.subscribe((b) => this.onBroadcast (b)); 
} 

onButtonClick (evt) { 
    // Any component anywhere that has subscribed 
    // to this emitter will hear this event, e.g. the parent or whatever 
    // andwill hear it 
    this.broadcastListener.emit (evt); 
} 

// Only needed if the child subscribed to the parent's emitter 
onBroadcast (evt) { 
    // This will be the data that was sent by whatever button was clicked 
    // via the subscription to the Input event emitter (parent, app, etc). 
    console.log (evt); 
} 

ChildComponent.annotations = [ 
    new Component ({ 
    ... // TS would use an attribute for this 
    inputs: [ 'broadcastListener' ] 
    template: ` 
     <div click)="onButtonClick ($event)"> 
     ... 
     </div> 
    ` 
    }) 
]; 

пояснено более подробно здесь: (Peer События в угловыми 2):

www.tcoz.com/#/errata

+0

Обратите внимание, что существует рекомендация в отношении будущего, которую может изменить EventEmitter, поэтому вы можете использовать тему. Лично я буду беспокоиться об этом, когда это произойдет на самом деле, есть тонны образцов, использующих EventEmitter, но для полноты я решил, что упомянул бы об этом. –

Смежные вопросы