Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have done a lot of work with the new Angular2 Framework recently. While testing out some of the features, I ended up with the error:

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

While investigating the error itself I came to several solutions, like adding the 'directive: [NgStyle]' to the component, but this does not solve the problem.

The code is like following:

main.ts

import {bootstrap} from 'angular2/platform/browser';
import {App} from './app'

bootstrap(App).then(error => console.log(error));

app.ts

import { Component } from 'angular2/core';
import { Button } from './button';
import { NgStyle } from "angular2/common";

@Component({
    selector: 'app',
    template: '<h1>My First Angular 2 App</h1><button>Hello World</button>',
    directives: [Button, NgStyle]
})
export class App { }

button.ts

import {Component} from "angular2/core";
import {NgStyle} from "angular2/common";

@Component({
    selector: 'button',
    host: {
        '[ngStyle]': 'style()'
    },
    templateUrl: '<ng-content></ng-content>',
    directives: [NgStyle]
})
export class Button {
    style() {
        return {
            'background': 'red'
        }
    }
}

Thank you for your help.

like image 292
Marcel Jöstingmeier Avatar asked Apr 08 '16 15:04

Marcel Jöstingmeier


2 Answers

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.

like image 109
codef0rmer Avatar answered Sep 28 '22 05:09

codef0rmer


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.

like image 39
Günter Zöchbauer Avatar answered Sep 28 '22 04:09

Günter Zöchbauer