Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

angular - subscribe to valueChanges from input FormControl in FormGroup

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

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 }}
question from:https://stackoverflow.com/questions/45179389/subscribe-to-valuechanges-from-input-formcontrol-in-formgroup

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you are missing some thing here with formGroup and formControlName you should do:

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

on 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

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...