Skip to content
This repository was archived by the owner on Dec 4, 2017. It is now read-only.
This repository was archived by the owner on Dec 4, 2017. It is now read-only.

StyleGuide - In Directives and Components, "Use @HostListener..." #1157

Closed
@mgechev

Description

@mgechev

To be discussed.

// cc @johnpapa @wardbell


  • Use @HostListener and @HostBinding instead of the host property of the @Directive and @Component decorators:

    Why?: The name of the property, or method name associated to @HostBinding or respectively @HostListener should be modified only in a single place - in the directive's controller. In contrast if you use host you need to modify both the property declaration inside the controller, and the metadata associated to the directive.

    Why?: The metadata declaration attached to the directive is shorter and thus more readable.

    /* AVOID */
    @Directive({
      selector: '[sgSample]',
      host: {
        '(mouseenter)': 'onMouseEnter()',
        'attr.role': 'button'
      }
    })
    class SampleDirective {
      role = 'button';
      onMouseEnter() {...}
    }
    /* RECOMMENDED */
    @Directive({
      selector: '[sgSample]'
    })
    class SampleDirective {
      @HostBinding('attr.role') role = 'button';
      @HostListener('mouseenter') onMouseEnter() {...}
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions