如何在模型更新时触发事件

时间:2016-05-23 08:14:07

标签: angular observable

我想在视图中更新模型中的任何值时触发事件。

我试图利用observable作为休闲。

export class requestsComponent implements OnInit {

    private filter: Observable<{
        name: string;
        phone: number;
        email: string;
        agent: string;
    }>;
    constructor( @Inject(BookSiteVisitService) private bookSiteVisitService: BookSiteVisitService) {

        this.filter = new Observable(observer => {
        });
        this.filter.subscribe(
            value => {
                console.log(value);
            },
            error => { console.log(error) },
            () => {
                console.log('conmplete');
            }
        );
    }
    ngOnInit() {

    }

}

我有想要观察者的过滤器对象如果过滤器中有任何更新我有相应的处理ui的更新功能

<tbody>
    <tr>
        <td><input type="text" [(ngModel)]="filter.name" class="form-control"></td>
        <td><input type="text" [(ngModel)]="filter.phone" class="form-control"></td>
        <td><input type="text"  [(ngModel)]="filter.email"  class="form-control"></td>
        <td></td>
        <td><input type="text" [(ngModel)]="filter.agent" class="form-control"></td>
    </tr>
    <tr *ngFor="let request of requests">
        <td>{{request.customerName}}</td>
        <td>{{request.phone}}</td>
        <td>{{request.email}}</td>
        <td>{{request.comment}}</td>
        <td>{{request.representativeName}}</td>
        <td>{{request.requestType}}</td>
    </tr>    
</tbody>

1 个答案:

答案 0 :(得分:1)

您可以使用ngModelChange事件:

<td>
  <input type="text"
    [(ngModel)]="filter.name"
    (ngModelChange)="onChange()" <--------
    class="form-control">
</td>

另一种选择是利用ngDoCheck钩子方法和KeyValueDiffers类。这是一个示例:

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

ngDoCheck() {
  var changes = this.differ.diff(this.filter);
  if (changes) {
    changes.forEachChangedItem((elt) => {
      if (elt.key === 'name') {
        (...)
      }

      if (elt.key === 'phone' ) {      
        (...)
      }

      (...)
    });
  }
}

有关详细信息,请参阅此链接: