Angular2异常:无法绑定到'ngStyle',因为它不是已知的本机属性

Mar*_*ier 13 typescript angular

我最近使用新的Angular2框架做了很多工作.在测试一些功能时,我最终得到了错误:

无法绑定到'ngStyle',因为它不是已知的本机属性

在调查错误本身时,我遇到了几个解决方案,比如在组件中添加'directive:[NgStyle]',但这并没有解决问题.

代码如下:

main.ts

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

bootstrap(App).then(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)

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 { }
Run Code Online (Sandbox Code Playgroud)

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'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助.

cod*_*mer 29

当您不导入CommonModule模块时会发生这种情况.在最新版本的Angular中,所有DOM级别指令都归入同一模块下.

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

您可以导入NgClassNgStyle单独导入,但如果您最终在通过路由器访问的多个组件中使用相同的内容,Angular很快就会抛出错误.

  • 在哪里导入这个?在组件中还是在 app.module.ts 中? (2认同)
  • 导入app.module或您的自定义模块文件(如shared.module) (2认同)
  • 当您看到一个一眼就能解决您问题的答案时,真是太棒了。谢谢。 (2认同)

Gün*_*uer 5

如果您需要完全的灵活性,那么主机提供的

host: {
  '[class.someName]':'someValue',
  '[style.someProp]':'someValue'
}
Run Code Online (Sandbox Code Playgroud)

您需要使用命令式方法,例如

@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());
  }
}
Run Code Online (Sandbox Code Playgroud)

Renderer提供的其他方法。


Mar*_*ier 2

请注意,我在写这个问题时找到了解决方案。我喜欢分享它,这样其他人就不必永远寻找。

\n\n

请查看以下链接:

\n\n
\n

Angular2 异常:主机内的 ngClass,“不是已知的本机属性”

\n
\n\n

正如 \'G\xc3\xbcnter Z\xc3\xb6chbauer\' 所描述的,不可能在主机绑定中使用指令。他为 ngClass 提供了一个解决方案。

\n\n

这是我的问题的一个简单解决方案:

\n\n

按钮.ts

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

请注意,这不是一个完美的解决方案,因为它在将对象“编译”为纯 CSS 时缺乏。我只是替换所有出现的 \' " \',这会在使用 \'url(" "), ...\' 时导致奇怪的行为。\n希望我可以帮助有相同或类似问题的人。

\n

  • 由于不再使用“指令”,答案已过时 (5认同)