2017-12-04 3 views
0

@Input()デコレータをコンポーネントプロパティに適用してから、カスタムデコレータとチェーンします。PropertyDecorator内からコンポーネントのプロパティを読み取る

私のパブリックプロパティは、正しくバインドされていても読み込み/設定できないようです。この時点で私のコンポーネントのプロパティの読み取り/書き込みする方法

例えば

私の言語のデコレータで次に
@Input() 
    @Language('global.pw.current') 
    public existingPasswordLabel: string; 

export function Language(keyId: string): PropertyDecorator { 
    return (target: any, key: string) => { 
    setTimeout(()=>{ 
     console.log(target[key]); //This is never set but is on screen 
     // in fact none of my public component properties are on the target 
    },1000); //Plenty of delay to make sure binding has happened 
    }; 
} 

+0

@inputデコレータの実装は、オブジェクトのsetとget paramsをオーバーライドしていると思います。 – DmitriyKhirniy

答えて

2

オブジェクトはクラスのインスタンスではなく、クラスそのものであり、設定しようとしているプロパティがクラスのインスタンス上にあるため、target[key]は決して設定されません本質Class[key]

あなたが財産を取得するときにアクセスを持っているので、財産になるようにフィールドを上書きしようとすることができますが、設定/

export function Language(keyId: string): PropertyDecorator & MethodDecorator { 
    return (target: any, key: string, desc?: PropertyDescriptor) => { 
     desc = desc || { 
      get: function() { 
       return this["_" + key]; 
      }, 
      configurable: true, 
      enumerable: true 
     }; 

     let baseSetter = desc.set || function (value) { 
      this["_" + key] = value; 
     }; 

     desc.set = function (value) { 
      console.log(`Value of ${key} is ${value} with ${keyId}`); 
      baseSetter.call(this, value); 
     }; 
     // We return the property descriptor which will be used to define the property using Object.defineProperty in the __decorate helper 
     return desc; 
    }; 
} 
class ChildComponent { 
    @Language('global.pw.current') 
    @Input() 
    public existingPasswordLabel: string; 
    // Works with properties as well 
    private _title: string; 
    @Language('global.title') 
    @Input() 
    public get title(): string { 
     return this._title; 
    } 
    public set title(value: string) { 
     this._title = value; 
    } 
} 

注:私は@Inputデコレータでテストしていないを追加しかし、それはうまくいくはずです。

編集:デコレータ@Inputでテストされ、すべて正常に動作します。また、フィールドとプロパティの両方で動作するようにコードを更新しました。

関連する問題