20

私は最近、新しい Angular2 フレームワークで多くの作業を行いました。いくつかの機能をテストしているときに、次のエラーが発生しました。

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

エラー自体を調査しているときに、「ディレクティブ: [NgStyle]」をコンポーネントに追加するなど、いくつかの解決策にたどり着きましたが、これでは問題は解決しません。

コードは次のようになります。

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 { }

ボタン.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'
        }
    }
}

ご協力ありがとうございました。

4

4 に答える 4

5

ホストが提供するものに対して、完全な柔軟性が必要な場合

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

次のような命令的な方法を使用する必要があります

@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());
  }
}

またはRendererが提供する他のメソッド。

于 2016-04-08T15:41:26.483 に答える
2

この質問を書いているときに解決策を見つけたことに注意してください。そして、他の人が永遠に探す必要がないように、私はそれを共有したいと思っています.

次のリンクをご覧ください。

Angular2 例外: ホスト内の ngClass、「既知のネイティブ プロパティではありません」

「Günter Zöchbauer」が説明しているように、ホスト バインディングでディレクティブを使用することはできません。そして、彼は ngClass のソリューションを提供しています。

そして、ここに私の問題の簡単な解決策があります:

ボタン.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, '');
    }
}

これは、オブジェクトを単純な css に「コンパイル」するときに欠けているため、完全な解決策ではないことに注意してください。「url(" ")、...」を使用すると奇妙な動作を引き起こす「 "」の出現をすべて置き換えるだけです。同じまたは類似の質問で誰かを助けることができることを願っています。

于 2016-04-08T15:33:57.630 に答える