首页 文章

角度属性选择器:输出绑定不起作用

提问于
浏览
2

我有2个组件:列表和行 .

在列表组件的模板中,我使用表并使行与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>

Here's the problem :当在行上按下删除按钮时,将调用行组件上的处理程序:

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

这很好 . 但是,当尝试触发 Launcher 时,它永远不会到达父级 . 在浏览器控制台中查看,我看到以下错误:

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'函数 .

任何人都可以帮我解决这个问题或建议修复吗?

非常感激 .

1 回答

  • 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);
      }
    }
    

相关问题