如何观察 Angular 中的表单变化 [英] How to watch for form changes in Angular

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

问题描述

在 Angular 中,我可能有一个看起来像这样的表单:

In Angular, 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 上的 Angular 示例.

我无法弄清楚如何在 Angular 中完成同样的事情.显然,我们不再有$scope、$rootScope.肯定有一种方法可以完成同样的事情吗?

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

这是一个 关于 Plunker 的 Angular 示例.

推荐答案

UPD. 更新了答案和演示以与最新的 Angular 保持一致.

UPD. The answer and demo are updated to align with latest Angular.

您可以订阅整个表单更改,因为 FormGroup 提供 valueChanges 属性,它是一个 Observerable 实例:

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

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

在这种情况下,您需要使用 表单生成器.像这样:

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

export class App {
  constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })

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

在这个演示中查看valueChanges的实际效果:http://plnkr.co/edit/xOz5xaQyMlRzSrgtt7Wn?p=preview

Check out valueChanges in action in this demo: http://plnkr.co/edit/xOz5xaQyMlRzSrgtt7Wn?p=preview

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

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