1

In Angular 8 I have had time and time again the need to simply associate a class or classes to the host element of a component which zero conditional logic behind it. For example, I might want my component or directive:

<app-button>Click Me</app-button>

To always have the class btn on it no matter what. I dont want to force a developer to have to do:

<app-button class="btn">Click Me</app-button>

As that leads to people forgetting it, mistyping the class name and just not being DRY when we can be.

So that leads me to want to use the host property on the @Directive or @Component decorator in order to achieve this like so:

@Directive({
  selector: 'app-button',
  host: {
    class: 'btn'
  }
})

However, my TS linter has a rule no-host-metadata-property that was automatically set to true by default. After reading up on the subject in the post below I now understand why it is in some cases better to not use it since you can get stronger typing when using conditionals in the host key/value pairs. This makes total sense when you have something that complex, but in my case I have zero conditionals and I simply want my :host element to always have a class btn.

Use @HostBindings instead host in angular 4

With that said, why is this rule defaulted to true when we create Angular 8 projects using the Angular Workspaces? I never turned this on, but it was enabled by default and really takes away from the simple use case I pointed out above. Is there another way to do this without host metadata that doesn't look and feel funky like this:

@HostBinding('class.btn') get isBtn() {
    // This feels stupid and overly engineered for something so simple
    return true;
}

Is this just a silly rule and I should just manually disable it and move on or am I missing some vital piece of information here?

Matt Hintzke
  • 7,744
  • 16
  • 55
  • 113
  • check this:https://angular.io/guide/styleguide#style-06-03 – Chellappan வ Oct 10 '19 at 18:19
  • @Chellappan I read over that and I understand that it is "preferred", but this only seems to make sense when your using complex conditionals to decide the value of the attribute. When you just need a simple "class" hardcoded to an immutable value, it seems overkill to wire up the HostBinding, no? – Matt Hintzke Oct 10 '19 at 20:34
  • For simple scenario It's okay to use host meta data, Bcoz the only difference between hostdecorator and host meta data is @HostBinding only supports binding of values, while host metadata supports both binding and static values. – Chellappan வ Oct 11 '19 at 04:17

0 Answers0