角度2 +离子2:检测对象是否被修改

Dav*_*ave 7 typescript ionic-framework ionic2 ionic3 angular

问)如果我有一个带有大量属性的对象,所有属性都绑定到表单中的字段,那么当对象发生变化时如何捕获?

我不想把(blur)事件放在每个字段上,因为页面已经很重,这可能导致页面上的监听器太多.

例如

宾语:

var person = {
    name: string,
    email: string,
    phone: string
};
Run Code Online (Sandbox Code Playgroud)

形成:

<input [(ngModel)]="person.name" type="text" />
<input [(ngModel)]="person.email" type="text" />
<input [(ngModel)]="person.phone" type="text" />
Run Code Online (Sandbox Code Playgroud)

seb*_*ras 11

然而,理想情况下我需要另一种方式,比如角度1 $ watch,因为我可以通过其他方式更改复杂对象,而不仅仅是简单的输入字段

我正在使用Google自动填充功能Component,我正在处理类似的问题:当用户键入地址并从Google建议中选择一个地址时,我需要更新其他一些字段(例如城市,省份,邮政编码等) ).

就像@GünterZöchbauer所说,我创建了一个observable以便知道我的自动完成时有什么变化component,但第二个问题是当发生这种情况时视图没有被更新.那是因为一些非常有趣和强大的东西叫做Zones.如果这个概念对您来说是新的,请参考这里这里获得一个很好的解释.

你可以在那里看到,

应用程序状态更改由三件事引起:

1)事件 - 用户事件,如点击,更改,输入,提交,......

2)XMLHttpRequests - 例如从远程服务定时器获取数据时 -

3)setTimeout(),setInterval(),因为JavaScript

...事实证明,当Angular真正对更新视图感兴趣时,这些是唯一的情况.

因此,如果

还有其他方法可以改变我的复杂对象

你必须让Angular知道某些事情发生了变化,并且需要我们知道更新事情.这就是我做的:

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AutocompleteService {

    private autocompleteObserver: any;
    public autocomplete: any;

    constructor(...) {
        this.autocompleteObserver = null;

        this.autocomplete = Observable.create(observer => {
            this.autocompleteObserver = observer;
        });
    }

    public initializeAutocomplete(element): void { 

        // Where all the magic happens
        // ...

        // Send informtaion back to the caller
        this.autocompleteObserver.next(addressInformation);
    }
Run Code Online (Sandbox Code Playgroud)

然后在我的页面中.ts:

import { Component, NgZone } from '@angular/core';
import { AutocompleteService } from '../../providers/autocomplete-service/autocomplete-service';

@Component({
  templateUrl: 'build/pages/my-new-page/my-new-page.html',
  directives: [FORM_DIRECTIVES],
  providers: [AutocompleteService]
})
export class MyNewPage {

    constructor(..., private autocompleteService : AutocompleteService) {

        // Initialize all the things you need
        // ... 

       this.autocompleteService.autocomplete.subscribe((addressInfo) => {
            this.ngZone.run(() => {
                // Update the fields of the form, and Angular will update
                // the view for you.
                this.updateAddress(addressInfo);
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,通过在角度区域内执行一些代码,您告诉Angular它需要知道这些更改,因为事情可能需要更新.


Aar*_*ers 1

您可以使用表单对象并检查表单是否已更改。

我知道最新版本的 Angular2 和 Ionic2 以及新的 Forms 模块存在一些问题,但这是我的建议。

https://angular.io/docs/ts/latest/guide/forms.html