From 13ecc140e8f5abcf9d5bf5616a4d7156c69d6c02 Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Fri, 7 Oct 2016 13:53:53 -0700 Subject: [PATCH] fix(compiler): validate `@HostBinding` name (#12139) relates to #7500 --- .../compiler/src/directive_resolver.ts | 7 ++++++ .../compiler/test/directive_resolver_spec.ts | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/modules/@angular/compiler/src/directive_resolver.ts b/modules/@angular/compiler/src/directive_resolver.ts index 5b473c86a7..3d54f80b17 100644 --- a/modules/@angular/compiler/src/directive_resolver.ts +++ b/modules/@angular/compiler/src/directive_resolver.ts @@ -71,6 +71,13 @@ export class DirectiveResolver { } else if (a instanceof HostBinding) { const hostBinding: HostBinding = a; if (hostBinding.hostPropertyName) { + const startWith = hostBinding.hostPropertyName[0]; + if (startWith === '(') { + throw new Error(`@HostBinding can not bind to events. Use @HostListener instead.`); + } else if (startWith === '[') { + throw new Error( + `@HostBinding parameter should be a property name, 'class.', or 'attr.'.`); + } host[`[${hostBinding.hostPropertyName}]`] = propName; } else { host[`[${propName}]`] = propName; diff --git a/modules/@angular/compiler/test/directive_resolver_spec.ts b/modules/@angular/compiler/test/directive_resolver_spec.ts index 7e75be9e1d..d061c16c17 100644 --- a/modules/@angular/compiler/test/directive_resolver_spec.ts +++ b/modules/@angular/compiler/test/directive_resolver_spec.ts @@ -117,6 +117,18 @@ class SomeDirectiveWithSameHostBindingAndInput { @Input() @HostBinding() prop: any; } +@Directive({selector: 'someDirective'}) +class SomeDirectiveWithMalformedHostBinding1 { + @HostBinding('(a)') + onA() {} +} + +@Directive({selector: 'someDirective'}) +class SomeDirectiveWithMalformedHostBinding2 { + @HostBinding('[a]') + onA() {} +} + class SomeDirectiveWithoutMetadata {} export function main() { @@ -210,6 +222,17 @@ export function main() { expect(directiveMetadata.host) .toEqual({'(c)': 'onC()', '(a)': 'onA()', '(b)': 'onB($event.value)'}); }); + + it('should throw when @HostBinding name starts with "("', () => { + expect(() => resolver.resolve(SomeDirectiveWithMalformedHostBinding1)) + .toThrowError('@HostBinding can not bind to events. Use @HostListener instead.'); + }); + + it('should throw when @HostBinding name starts with "["', () => { + expect(() => resolver.resolve(SomeDirectiveWithMalformedHostBinding2)) + .toThrowError( + `@HostBinding parameter should be a property name, 'class.', or 'attr.'.`); + }); }); describe('queries', () => {