Angular2 作用域和组件

Angular2 scope's and components

全部,

这是我的:

用户-list.component.ts

export class UserListComponent {

    public userSerivce: UserService;

    public deleteUser(id) {
        this.userSerivce.delete(id);
    }
}

用户-list.component.html

<div>
    <some-reusable[deleteFunc]="delete" > </some-reusable><!-- this will bind "delete" on the user- list.component, to "deleteFunc" on  SomeReusableComponent-->
</div>

一些-reusable.component.ts

export class SomeReusableComponent {    
    @Input() deleteFunc: Function;    
}

一些-reusable.component.html

<button type="button" (click)="deleteFunc(entityId)" aria-label="Delete" >
    <span class="glyphicon glyphicon-trash" aria-hidden="true"> </span>
</button>

这是我的问题:

当我单击按钮时,它会调用 UserListComponent 上的函数就好了,但是当提到 this 时,它也提到了 SomeReusableComponent,我明白为什么会这样,但我正在寻找解决方案?您可以在上面的示例中看到对 this.userSerivce.delete(id); 的调用将失败,因为 userServiceSomeReusableComponent.

上不存在

我希望上面的例子有意义。

谢谢

史蒂夫

我认为更好的方法是使用事件绑定

export class SomeReusableComponent {    
    @Output itemDeleted:EventEmitter = new EventEmitter();

    handleDelete(entityId) {
      itemDeleted.emit(entityId);
    }
}
<button type="button" (click)="handleDelete(entityId)" aria-label="Delete" >
    <span class="glyphicon glyphicon-trash" aria-hidden="true"> </span>
</button>
<some-reusable (itemDeleted)="delete($event)" > </some-reusable>

完全同意@Günter!

关于您的 this 问题,这是因为您在引用函数(即使是从对象)时丢失了 this。为了防止这种情况,您可以使用函数的 bind 方法:

delete.bind(this)