如何在Angular中监视表单更改 [英] How to watch for form changes in 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中完成相同的事情时遇到了麻烦.显然,我们不再有$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上的角度示例.
推荐答案
UPD.答案和演示已更新为与最新的Angular保持一致.
UPD. The answer and demo are updated to align with latest Angular.
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));
在这种情况下,您将需要使用 FormBuilder .像这样:
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屋!