在AngularJS中,你可以使用$scope的$watch函数指定观察者来观察作用域变量的变化。在Angular中,什么与监视变量变化(比如组件变量)是等价的?


当前回答

下面是为模型使用getter和setter函数的另一种方法。

@Component({
  selector: 'input-language',
  template: `
  …
  <input 
    type="text" 
    placeholder="Language" 
    [(ngModel)]="query" 
  />
  `,
})
export class InputLanguageComponent {

  set query(value) {
    this._query = value;
    console.log('query set to :', value)
  }

  get query() {
    return this._query;
  }
}

其他回答

这并没有直接回答这个问题,但我在不同的情况下遇到过这个Stack Overflow问题,以解决我在angularJs中使用$watch的问题。我最终使用了另一种方法,而不是目前的答案中所描述的方法,并且想要分享它,以防有人发现它有用。

我用来实现类似$watch的技术是在Angular服务中使用一个BehaviorSubject(这里有更多关于这个主题的内容),并让我的组件订阅它,以便获得(监视)更改。这类似于angularJs中的$watch,但需要更多的设置和理解。

在我的组件中:

export class HelloComponent {
  name: string;
  // inject our service, which holds the object we want to watch.
  constructor(private helloService: HelloService){
    // Here I am "watching" for changes by subscribing
    this.helloService.getGreeting().subscribe( greeting => {
      this.name = greeting.value;
    });
  }
}

为我服务

export class HelloService {
  private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
  constructor(){}
  // similar to using $watch, in order to get updates of our object 
  getGreeting(): Observable<{value:string}> {
    return this.helloSubject;
  }
  // Each time this method is called, each subscriber will receive the updated greeting.
  setGreeting(greeting: string) {
    this.helloSubject.next({value: greeting});
  }
}

这是一个关于Stackblitz的演示

这个行为现在是组件生命周期的一部分。

组件可以在OnChanges接口中实现ngOnChanges方法来访问输入更改。

例子:

import {Component, Input, OnChanges} from 'angular2/core';


@Component({
  selector: 'hero-comp',
  templateUrl: 'app/components/hero-comp/hero-comp.html',
  styleUrls: ['app/components/hero-comp/hero-comp.css'],
  providers: [],
  directives: [],

  pipes: [],
  inputs:['hero', 'real']
})
export class HeroComp implements OnChanges{
  @Input() hero:Hero;
  @Input() real:string;
  constructor() {
  }
  ngOnChanges(changes) {
      console.log(changes);
  }
}

如果你想让它双向绑定,你可以使用[(yourVar)],但你必须实现yourVarChange事件,并在每次变量改变时调用它。

像这样的东西来跟踪英雄的变化

@Output() heroChange = new EventEmitter();

然后当你的英雄发生变化时,调用this.heroChange.emit(this.hero);

[(英雄)]绑定将为您完成其余的工作

请看例子:

http://plnkr.co/edit/efOGIJ0POh1XQeRZctSx?p=preview

下面是为模型使用getter和setter函数的另一种方法。

@Component({
  selector: 'input-language',
  template: `
  …
  <input 
    type="text" 
    placeholder="Language" 
    [(ngModel)]="query" 
  />
  `,
})
export class InputLanguageComponent {

  set query(value) {
    this._query = value;
    console.log('query set to :', value)
  }

  get query() {
    return this._query;
  }
}

如果除自动双向绑定外,还希望在值更改时调用函数,则可以将双向绑定快捷语法转换为更详细的版本。

<input [(ngModel)]=“yourVar”></input>

是简写

<input [ngModel]=“yourVar” (ngModelChange)=“yourVar=$event”></input>

(参见http://victorsavkin.com/post/119943127151/angular-2-template-syntax)

你可以这样做:

<input [(ngModel)]=“yourVar” (ngModelChange)=“changedExtraHandler($event)”></input>