2017-05-03 41 views
1

我有兩個部分組成:一個列表和行。角屬性選擇:輸出綁定不工作

在列表組件的模板,我用一個表,以便與ngFor行工作,我不得不使用屬性選擇的子組件(即用方括號):

@Component({ 
    selector: '[my-tr]' 
. 
. 
}) 

的子組件也有被聲明,初始化,然後燒製後按下按鈕輸出:

@Output() onItemDeleted: EventEmitter<SubscriberListItem>; 
.. 
this.onItemDeleted = new EventEmitter<SubscriberListItem>(); 
.. 
this.onItemDeleted.emit(this.item); 

然後父組件上,該模板包括把孩子當作一個錶行如下:

<table> 
<tbody> 
<tr my-tr *ngFor="let item of items" [item]="item" (onItemDeleted)="removeItem($event)"></tr> 
</tbody> 
</table> 

下面是該行的模板:

<td width="25%">{{item.name}}</td> 
<td width="40%">{{item.street}}</td> 
<td width="5%">{{item.postCode}}</td> 
<td width="30%"> 
    <button (click)="removeItem($event)">DELETE</button>   
</td> 

這裏的問題:當按下行刪除按鈕,該行組件上的處理程序被調用:

removeItem(event: any): void { 
    this.onItemDeleted.emit(this.item); 
} 

這很好。但是,試圖點燃發射器時,它永遠不會到達父級。展望在瀏覽器控制檯,我看到了以下錯誤:

ERROR TypeError: co.removeItem is not a function 
    at Object.eval [as handleEvent] (SubscribersListComponent.html:191) 
    at handleEvent (core.es5.js:11799) 
    at callWithDebugContext (core.es5.js:13007) 
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:12595) 
    at dispatchEvent (core.es5.js:8773) 
    at core.es5.js:10638 
    at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3840) 
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:236) 
    at SafeSubscriber.next (Subscriber.js:185) 
    at Subscriber._next (Subscriber.js:125) 
    at Subscriber.next (Subscriber.js:89) 
    at EventEmitter.Subject.next (Subject.js:55) 
    at EventEmitter.emit (core.es5.js:3814) 
    at SubscriberRowComponent.webpackJsonp.537.SubscriberRowComponent.removeItem (subscriber-row.component.ts:35) 
    at Object.eval [as handleEvent] (SubscriberRowComponent.html:7) 

這事做的事實,我對孩子的成分錶行使用屬性選擇。輸出該行綁定的上下文是不是父組件,因此不找到「的removeItem」功能。

誰能幫我解決這個問題或建議修復?

非常感謝。

回答

0

不知道如果我正確地給你,但這裏是工作的一個簡單的例子:

@Component({ 
    selector: '[my-tr]', 
    template: '{{item}} <button (click)="removeItem($event)">DELETE</button>' 
}) 
export class MyTr { 
    @Input() item: any; 
    @Output() onItemDeleted = new EventEmitter<any>; 

    removeItem(event: any): void { 
    this.onItemDeleted.emit(this.item); 
    } 
} 
@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <div my-tr *ngFor="let item of items" [item]="item" (onItemDeleted)="removeItem($event)"></div> 
    </div> 
    `, 
}) 
export class App { 
    items = ['a', 'b', 'c']; 

    name:string; 
    constructor() { 
    this.name = `Angular! v${VERSION.full}` 
    } 

    removeItem(item) { 
    console.log('removeItem', item); 
    } 
}