我有2个组件:列表和一个行。
在列表组件的模板中,我使用表并使该行与NGFOR一起使用,我必须为子组件使用属性选择器(即使用Square Brackets(:
@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"函数。
谁能帮助我解决此问题或建议修复?
非常感谢。
不确定我是否正确地找到了您,但这是一个有效的简化示例:
@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);
}
}