如何来观察角2形式的变化? [英] How to watch for form changes in Angular 2?

查看:109
本文介绍了如何来观察角2形式的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角1.x中,我可能有一个看起来像这样的形式:

In Angular 1.x, I might have a form that looks like this:

<ng-form>
    <label>First Name</label>
    <input type="text" ng-model="model.first_name">

    <label>Last Name</label>
    <input type="text" ng-model="model.last_name">
</ng-form>

在相应的控制器,我可以很容易地观看像这样的变化这种形式的内容:

Within the corresponding controller, I could easily watch for changes to the contents of that form like so:

function($scope) {

    $scope.model = {};

    $scope.$watch('model', () => {
        // Model has updated
    }, true);

}

下面是对的jsfiddle 一个 1.X的例子。

Here is a 1.X example on JSFiddle.

我无法搞清楚如何实现在角2.同样的事情很明显,我们不再有 $范围,等等,但肯定有是一种方法,通过它同样的事情可以完成?

I'm having trouble figuring out how to accomplish the same thing in Angular 2. Obviously, we no longer have $scope, etc..., but surely there is a method by which the same thing can be accomplished?

下面是Plunker 一个 2.X的例子。

Here is a 2.X example on Plunker.

推荐答案

实际上,你可以订阅整个造型的变化,由于到的ControlGroup 重新presenting形式有 valueChanges 属性,它是一个Observerable例如:

You can actually subscribe to entire form changes due to the fact that ControlGroup representing a form has valueChanges property which is an Observerable instance:

this.form.valueChanges.subscribe(data => console.log('form changes', data));

在这种情况下,您将需要手动构造形式使用 FormBuilder 。事情是这样的:

In this case you would need to construct form manually using FormBuilder. Something like this:

import {FORM_DIRECTIVES, FormBuilder} from 'angular2/common';

@Component({
    'selector': 'my-form',
    'templateUrl': 'template.html',
    'directives': [NgFor, FORM_DIRECTIVES]
})
class MyForm {

    constructor(formBuilder: FormBuilder) {

        this.form = formBuilder.group({
            firstName: 'Thomas',
            lastName: 'Mann'
        });

        this.form.valueChanges.subscribe(data => console.log('form changes', data));
    }

    onSubmit() {
        this.output = JSON.stringify(this.form.value, null, 4);
    }

}

和模板中同时声明 ngFromModel ngFormControl 属性:

and in template declare both ngFromModel and ngFormControl properties:

<form [ngFormModel]="form" (ngSubmit)="onSubmit()">

    <div class="form-group">
        <label>First Name</label>
        <input type="text" class="form-control" required [ngFormControl]="form.controls.firstName">
    </div>

    <div class="form-group">
        <label>Last Name</label>
        <input type="text" class="form-control" required [ngFormControl]="form.controls.lastName">
    </div>

    <button type="submit" class="btn btn-default">Submit</button>

</form>

演示: http://plnkr.co/edit/qJ53lG0apme2DsW909fy?p=$p$pview

这篇关于如何来观察角2形式的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆