Conditional style for host element

I have a component that all it does is do something like this:

@Component({ selector: 'my-comp', host: ???, template: ` <ng-content></ng-content> ` }) export default class MyComp { @Input() title: string; public isChanged: boolean; } 

The component has an isChanged property, and I want to apply a style to the host element based on this isChanged property. Is it possible?

+5
source share
3 answers

The class and style prefix is โ€‹โ€‹used for this. Here is an example:

 @Component({ selector: 'my-comp', host: { '[class.className]': 'isChanged' }, template: ` <ng-content></ng-content> ` }) export default class MyComp { @Input() title: string; public isChanged: boolean; } 

See Gรผnter answer for more:

+5
source

Not sure what you are trying to do, but something like this should be enough if you use ngAfterViewInit and ElementRef :

 import {AfterViewInit, ElementRef} from '@angular/core'; @Component({ selector: 'my-comp', host: ???, template: ` <ng-content></ng-content> ` }) export default class MyComp implements AfterViewInit { @Input() title: string; public isChanged: boolean; constructor(private _ref: ElementRef) {} ngAfterViewInit() { var host = this._ref.nativeElement; if (this.isChanged) { host.style.width = '200px'; } } } 

If you want to do some checking for isChanged every time it changes, you can implement ngDoCheck instead:

 ngDoCheck() { if (this.isChanged !== this.previousIsChanged) { var host = this._ref.nativeElement; if (this.isChanged) { host.style.width = '200px'; } } } 
0
source

I think you want your component to fire an event that might be captured by the host (and possibly transmit some data with it).

To do this, you will have the @output property, for example:

 @Output() isChanged: EventEmitter<any> = new EventEmitter() 

then in your code you could do:

 this.isChanged.emit(some value to pass) 

And catch it like this:

 (isChanged)="doSomething($event)" 
0
source

All Articles