简体   繁体   English

从FormGroup的输入FormControl订阅valueChanges

[英]subscribe to valueChanges from input FormControl in FormGroup

In Angular 4, I'm trying to subscribe to the valueChanges of a FormControl. 在Angular 4中,我尝试订阅FormControl的valueChanges。 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. 我输入时,form.value JSON正在更新,但订阅无法正常工作。

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)
});

Here's a template snippet. 这是一个模板片段。

<form #myForm="ngForm">

<md-input-container>
    <input mdInput name="firstName" [(ngModel)]="firstName" placeholder="enter name"/>
</md-input-container>
{{ myForm.value | json }}

I think you are missing some thing here with formGroup and formControlName you should do: 我认为您在这里缺少与formGroupformControlName东西:

myForm: FormGroup;
firstName = '';
lastName = '';

on ngOnInit ngOnInit

this.myForm = this.formBuilder.group({
    firstName: [this.firstName],
    lastName: [this.lastName]
});

this.myForm.controls['firstName'].valueChanges.subscribe(value => {
  console.log(value);
});

and In HTML 和在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>

You are missing some crucial things in your code. 您在代码中丢失了一些关键的东西。 First of all, what you are trying to subscribe to, doesn't exist. 首先,您要订阅的内容不存在。 You have not marked that field to be a formcontrol, so Angular doesn't know to subscribe to that. 您尚未将该字段标记为表单控件,因此Angular不知道订阅该控件。 You need to mark formControlName="firstname" to let Angular know it's a form control. 您需要标记formControlName="firstname"以使Angular知道它是一个表单控件。

Also you are missing marking your form as a form group, it should be: 另外,您也缺少将表单标记为表单组的信息,它应该是:

<form [formGroup]="myForm">

Using ngModel in forms is discouraged, the ngModel directive isn't even included in ReactiveFormsModule . 不建议在表单中使用ngModelReactiveFormsModule甚至不包含ngModel指令。 I have also noticed that it often causes issues when used together with reactive forms. 我还注意到,与反应形式一起使用时,它经常会引起问题。 You have the form controls there to replace the use of ngModel , so drop it and make use of the form controls, since they are already in place! 您在那里拥有表单控件来替换ngModel ,因此将其放下并使用表单控件,因为它们已经就位! :) :)

Then I would instead of using valueChanges just use some change event instead in the template, but it's up to you. 然后,我将不使用valueChanges而是在模板中使用一些change事件,但这取决于您。

So, the build of the form should look like this: 因此,表单的构建应如下所示:

this.myForm = this.formBuilder.group({
  firstname: [''],
  lastname: ['']
})
// I like to use variables
this.firstNameCtrl = this.myForm.get('firstname')

// as mentioned, like to use change event:
logValue(value) {
  console.log(value)
}    

The template would then look like this: 模板将如下所示:

<form [formGroup]="myForm">
  <md-input-container>
    <input mdInput formControlName="firstname" 
         (keyup)="logValue(firstNameCtrl.value)" />
  </md-input-container>  
  <md-input-container>
    <input mdInput formControlName="lastname"/>
  </md-input-container>   
</form>

So as mentioned use the form controls. 因此,如前所述,使用表单控件。 If you need an initial value, set them in the build of the form. 如果需要初始值,请在表单的构建中进行设置。 You have all values in your form object and you can access the values if you wish. 您在表单对象中拥有所有值,并且可以根据需要访问这些值。

I gave up on FormGroup and FormBuilder and just used 我放弃了FormGroup和FormBuilder,只是使用了

HTML: HTML:

<input mdInput [formControl]="firstName"> 

App class: 应用类别:

firstName = new FormControl();

ngOnInit: ngOnInit:

this.firstName.valueChanges.subscribe(value => {
     console.log('name has changed:', value)
});

My test is currently broken with the error "No provider for NgControl" but I'll work on that next. 我的测试当前被破坏,并显示错误“没有提供NgControl的提供程序”,但接下来我将继续处理。 Update: I just needed to import ReactiveFormsModule in the TestBed 更新:我只需要在TestBed中导入ReactiveFormsModule

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM