Angular 2 attribute directive input values are undefined and not set correctly

Input()s aren’t available in the constructor. They are set by change detection, and change detection is run after the component is instantiated. The lifecycle hooks ngOnChanges (every update) and ngOnInit (once after the first ngOnChanges call) are called after change detection updated an input:

Change

constructor(private el: ElementRef){
    this.setElement();
}

to

constructor(private el: ElementRef) {};

ngOnInit() {
  this.setElement();
}

ngOnInit() is called after the inputs are initialized.


Instead of

this.el.nativeElement.style.color = this.colorHex;

it’s better to use

@HostBinding('style.color')
@Input() colorHex : string;

@HostBinding('style.font-family')
@Input() fontFamily : string;

@HostBinding('style.font-weight')
@Input() fontWeight : string;

@HostBinding('style.font-style')
@Input() fontStyle : string;

Actually I haven’t tried myself to add @HostBinding() and @Input() on the same field, but I don’t see why it wouldn’t work.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)