I have a component that all it does is render , its something like this:
@Component({
selector: \'my-comp\',
host: ???,
template: `
Not sure what you're trying to do but something like this should suffice where 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 could implement ngDoCheck
instead/as well:
ngDoCheck() {
if (this.isChanged !== this.previousIsChanged) {
var host = this._ref.nativeElement;
if (this.isChanged) {
host.style.width = '200px';
}
}
}
You use the class
and style
prefix for this. Here is a sample:
@Component({
selector: 'my-comp',
host: {
'[class.className]': 'isChanged'
},
template: `
<ng-content></ng-content>
`
})
export default class MyComp {
@Input() title: string;
public isChanged: boolean;
}
See the Günter's answer for more details:
The accepted solution is using the host
metadata property which goes against the rules of TSLint:
TSLint: Use @HostBinding or @HostListener rather than the
host
metadata property (https://angular.io/styleguide#style-06-03)
The same can be achieved using @HostBinding instead:
import { Component, HostBinding, Input } from '@angular/core';
@Component({
selector: 'my-comp',
template: `
<ng-content></ng-content>
`
})
export default class MyComp {
@Input() title: string;
public isChanged: boolean;
@HostBinding('class.className') get className() { return this.isChanged; }
}
I think you want to let your component fire an event that can be catched by the host (and possibly pass some data with it).
To do that you would have an @output property like:
@Output() isChanged: EventEmitter<any> = new EventEmitter()
then in your code you could do:
this.isChanged.emit(some value to pass)
And catch it like:
(isChanged)="doSomething($event)"