从FormGroup的输入FormControl订阅valueChanges [英] subscribe to valueChanges from input FormControl in FormGroup
本文介绍了从FormGroup的输入FormControl订阅valueChanges的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Angular 4中,我试图订阅FormControl的valueChanges.以下两个版本均不起作用.我没有看到任何错误.我输入时,form.value JSON正在更新,但是订阅无法正常工作.
In Angular 4, I'm trying to subscribe to the valueChanges of a FormControl. Neither of the versions below is working. I'm not seeing any errors. The form.value JSON is updating as I type, but the subscription isn't working.
myForm: FormGroup;
public firstName = new FormControl();
public lastName = new FormControl();
this.myForm = this.formBuilder.group({
firstName: '',
lastName: '',
});
this.myForm.controls.firstName.valueChanges.subscribe(value => {
console.log(value);
});
this.myForm.get('firstName').valueChanges.subscribe(value => {
console.log('name has changed:', value)
});
这是模板片段.
<form #myForm="ngForm">
<md-input-container>
<input mdInput name="firstName" [(ngModel)]="firstName" placeholder="enter name"/>
</md-input-container>
{{ myForm.value | json }}
推荐答案
我认为您在这里缺少formGroup
和formControlName
应该做的事情:
I think you are missing some thing here with formGroup
and formControlName
you should do:
myForm: FormGroup;
firstName = '';
lastName = '';
在ngOnInit
this.myForm = this.formBuilder.group({
firstName: [this.firstName],
lastName: [this.lastName]
});
this.myForm.controls['firstName'].valueChanges.subscribe(value => {
console.log(value);
});
和在HTML
<form [formGroup]="myForm">
...
<input name="firstName" [(ngModel)]="firstName" formControlName="firstName" placeholder="enter name"/>
<input name="lastName" [(ngModel)]="lastName" formControlName="lastName" placeholder="enter last name"/>
...
</form>
这篇关于从FormGroup的输入FormControl订阅valueChanges的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文