Angular2: Unsubscribe from host listener [duplicat

2019-09-10 08:57发布

问题:

This question already has an answer here:

  • Programmatically (un)register to event with Angular 2 2 answers

If I subscribe to an event in an Angular2 component using host{}, how can I unsubscribe from the event?

@Component({
    selector: "foo",
    host: {
        "(window:resize)": "doSomething($event)"
    }
});

I've tried to use $event to unsubscribe, but the event itself never presents the scenario in which I want to unsubscribe.

For now, I'm just doing a poor man's short circuit, but I'd prefer to avoid the extra checks involved in short circuiting.

Poor man's short circuit:

private _conditionMet:boolean = false;
doSomething(e) {
    if(this._conditionMet) {
        return;
    }
    ...
}

somethingElse() {
    this._conditionMet = true;
}

回答1:

You can't unsubscribe from host-listener. If you need to unsubscribe you need to subscribe imperatively.

See also Programmatically (un)register to event with Angular 2