Angular2 Exception: Can't bind to 'ngStyle' since it isn't a known native property Angular2 Exception: Can't bind to 'ngStyle' since it isn't a known native property typescript typescript

Angular2 Exception: Can't bind to 'ngStyle' since it isn't a known native property


That happens when you do not import the CommonModule module. In the recent version of Angular, all DOM level directives are grouped under the same module.

import { CommonModule } from '@angular/common';

You can import NgClass or NgStyle individually but Angular soon throws an error if you end up using the same in multiple components accessed via router.


If you need full flexibility, over what host provides

host: {  '[class.someName]':'someValue',  '[style.someProp]':'someValue'}

you need to use imperative ways like

@Component({ ... }) export class SomeComponent {  constructor(private renderer:Renderer, private elementRef:ElementRef) {}  someMethod() {    this.renderer.setElementClass(        this.elementRef.nativeElement, this.getClassFromSomewhere());    this.renderer.setElementStyle(        this.element.nativeElement, 'background-color', this.getColor());  }}

or other methods Renderer provides.


Please note, i have found a solution, while writing this question. And i like to share it, so that other people do not have to search an eternity.

Please take a look at the following link:

Angular2 Exception: ngClass within a Host, "isn't a known native property"

As 'Günter Zöchbauer' describes, it is not possible to use directives in host bindings. And he comes with a solution for ngClass.

And here is a simple solution for my problem:

button.ts

import {Component} from "angular2/core";import {NgStyle} from "angular2/common";@Component({    selector: 'button',    host: {        '[style]': 'styleAsString()'    },    templateUrl: 'app/button.html',    directives: [NgStyle]})export class Button {    styleAsString() {        let style = {            background: 'red'        };        return JSON.stringify(style).replace('{', '').replace('}', '').replace(/"/g, '');    }}

Note, that this is not a perfect solution because it lacks while 'compiling' the object to plain css. I simply replace all occurences of ' " ' which results in an odd behaviour when using 'url(" "), ...'. Hope that i could help somebody with the same or a similar question.