Angular2异常:由于它不是已知的本机属性,因此无法绑定到"ngStyle" [英] Angular2 Exception: Can't bind to 'ngStyle' since it isn't a known native property
问题描述
最近我在新的Angular2框架上做了很多工作.在测试一些功能时,我最终遇到了错误:
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
在调查错误本身时,我想到了几种解决方案,例如在组件中添加指令:[NgStyle]",但这并不能解决问题.
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.
代码如下:
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'
}
}
}
谢谢您的帮助.
推荐答案
当您不导入 CommonModule
模块.在最新版本的Angular中,所有DOM级别的指令都分组在同一模块下.
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';
您可以导入 NgClass
或
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.
这篇关于Angular2异常:由于它不是已知的本机属性,因此无法绑定到"ngStyle"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!