我有两个组件:一个列表和一行。
在列表组件的模板中,我使用了一个表并使行与 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)
这与我在子组件的表格行上使用属性选择器这一事实有关。该行的输出绑定(bind)上下文不是父组件,因此它找不到“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);
}
}
关于 Angular 属性选择器 : Output Binding Not Working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43761737/