1

I read that its better to use @HostBinding instead of :host. So i think about change my component.ts

@Component({
    host: {
        'class': 'cover',
        '[class.uploading]': 'uploadProgress > 0',
    }
})

This works fine, but when i change it to:

export class Cover {
    @HostBinding('class') classes = 'mark6-cover';
    @HostBinding('[class.uploading]') uploadProgress > 0;

    @Input() uploadProgress = null;
}

i get errors and nothing works. What i did wrong here? And how can i make the variable uploadProgress to a observable?

Budi
  • 678
  • 2
  • 6
  • 27

1 Answers1

2

A counterpart to '[class.uploading]': 'uploadProgress > 0' would be:

@HostBinding('class.uploading')
@Input() 
uploadProgress = null;

uploadProgress input can be set asynchronously from observable subscription or elsewhere.

uploading class will be triggered for truthy uploadProgress, which is likely the expected behaviour.

In case the condition is different (e.g. input value can be negative, while a class should be triggered for positive values only), extra property can be added:

@Input() 
uploadProgress = null;

@HostBinding('class.uploading')
get isUploading() {
  return this.uploadProgress > 0;
}

If the condition is complex, it's preferable for a component to have OnPush change detection strategy.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thanks, but this overwrite the @Input() uploadProgress = null; And why i cant set Operators like > there? i tryed now !== null but this also dont work on this place... i need to set the class only if there is any activity on uploadProgress... And i need to remove it again when the progress is done. Can it be that this is simply not possible with @HostBinding? – Budi May 03 '18 at 22:10
  • Sure, @Input is needed there too. I added some explanation. Hope this helps. – Estus Flask May 03 '18 at 22:30
  • I thank you so much, but i cant make it work. i tryed with your bottom code example, but the class uploading is still missing when i add a dummy value from outside (like 33). And i use allready changeDetection: ChangeDetectionStrategy.OnPush – Budi May 03 '18 at 22:37
  • Thanks, now it works, i dont know why it yesterday dont. Maybe to tired ;) So you can confirm that @HostBinding is more dynamic than :host? – Budi May 04 '18 at 06:20
  • Glad you solved it. It's not more dynamic, it's more flexible. `host` is limited to expression string. – Estus Flask May 04 '18 at 06:33
  • Ah i see: https://angular.io/guide/styleguide#style-06-03 In some cases i dont need any big logic behind that var that i input from outside, but the docs says "be consistent in your choice." So you think its better when i use now everywhere @HostBinding and remove from all my files the :host? (to be consistent) – Budi May 04 '18 at 06:37
  • 1
    That's a matter of taste. I always use HostBinding, it's more expressive. You can also inherit it in child classes, IIRC. – Estus Flask May 04 '18 at 06:42