2016-05-01 15 views
5

Angular2/Typescriptでは、オブジェクトフィールドの変更を「観察」することは可能ですか?Angular2/Typescriptのオブジェクトフィールドの変更を聴く

たとえば、firstName、、およびfullNameというフィールドを持つクラスPersonがあるとします。 firstNameまたはlastNameのいずれかが変更されると、自動的にfullNameを更新できますか?このような

何か:

export class Person { 
    firstName: string= ''; 
    lastName: string = ''; 
    fullName: string = ''; 

    constructor(firstName: string, lastName: string) { 
    this.firstName.onChange(() => { this.updateFullName(); }); 
    this.lastName.onChange(() => { this.updateFullName(); }); 

    this.firstName = firstName; 
    this.lastName = lastName; 
    } 

    updateFullName() { 
    this.fullName = `${this.firstName} ${this.lastName}`; 
    } 
} 

答えて

7

まずアプローチ

後述のようにあなたは、姓と名とのfullNameを同期させるために活字体のセッター/ゲッターを活用できます。

get lastName() { 
    return this._lastName; 
} 

set lastName(lastName:string) { 
    this._lastName = lastName; 
    this.fullName = this._firstName + ' ' + this._lastName; 
} 

get firstName() { 
    return this._firstName; 
} 

set firstName(firstName:string) { 
    this._firstName = firstName; 
    this.fullName = this._firstName + ' ' + this._lastName; 
} 

この道をlastNameまたはfirstNameを設定すると、fullNameは自動的に更新されます。

var p = new Person(); 
p.lastName = 'last'; 
p.firstName = 'first'; 
console.log(p.fullName); // print 'first last' 

第二のアプローチ

デフォルトでAngular2は、オブジェクト内のプロパティの変更を定義することはできません。これは、参照の更新を検出するだけです。バインドされたプロパティのリファレンス(またはプリミティブ型の値)が更新されている場合を意味します。

これは、Angular2は、ngDoCheckフックメソッドを使用して独自の戦略をプラグインすることができます。

KeyValueDiffersクラス(注入する)を利用して、特定のオブジェクトの更新を検出することができます。

詳細はこちらのリンクを参照してください:

ここではサンプルです:

@Component({ 
    selector: 'my-component', 
    (...) 
}) 
export class MyComponent implements DoCheck { 
    @Input() person: Person; 
    differ: any; 

    constructor(differs: KeyValueDiffers) { 
    this.differ = differs.find([]).create(null); 
    } 

    ngDoCheck() { 
    var changes = this.differ.diff(this.person); 

    if (changes) { 
     changes.forEachChangedItem((elt) => { 
     if (elt.key === 'firstName' || elt.key === 'lastName') { 
      this.person.fullName = this.person.firstName + ' ' + this.person.lastName; 
     } 
     }); 
    } 
    } 
} 

prop1プロパティの値が更新されると、doSomethingIfProp1Change方法がありますと呼ばれる。

このplunkr:http://plnkr.co/edit/uvOKMXQa9Ik8EiIhb60Y?p=previewを参照してください。

+0

恐縮です、ありがとうございます。 – Fuzzley

+0

うん、ありがとう! 2番目のソリューションは、配列の変更をリッスンする唯一の方法ですか、btw? – Fuzzley

+0

素晴らしい!アレイやオブジェクト内の変更は可能ですが、これはAngular2の唯一の方法です。例えばngForとngClassはこのメカニズムに依存しています;-) ngOnChangesはこのケースでは適用されません... –

関連する問題