简体   繁体   中英

How to access form control and form group in angular reactive form

I would like to pipe a form group of a reactive form.

Then I would like to do some checks on this group separate controls.

Here is how I define my form

  myForm = this.formBuilder.group({
    myFormNameDrop: this.formBuilder.group({
      myName:['',Validators.required],
      myDrop:['era']
    }),    
    style:[''],
    userId:[this.user_id]
  });

And this is the pipe I try to create

this.results = this.myForm.value.myFormNameDrop.valueChanges.pipe(      
  debounceTime(400),
  distinctUntilChanged(),            
  filter(formdata => formdata.myName.length > 0),
  switchMap( formdata => this.shoesService.details(formdata.myName)),
  shareReplay(1)
);//pipe  

I get two errors. TypeError: Cannot read property 'pipe' of undefined about the this.results = this.myForm.value.myFormNameDrop.valueChanges.pipe(

and VS code shows a warning about the filter(formdata => formdata.myName.length > 0), : Property myName does not exists on type '{}'

How can I access formGroups and controls of formGroups in such cases? I use angular 6

Thanks

You are not fetching the form controls properly. Use get() method on FormGroup object to fetch formControl

this.results = this.myForm.get('myFormNameDrop').valueChanges.pipe(      
  debounceTime(400),
  .........................
);

EDIT :

To access myName you may do it as as follows :

this.myForm.get('myFormNameDrop').get('myName').value


Also If you are interested in just myName , then you could directly watch for valueChanges of myName , instead of watching myFormNameDrop

this.results = this.myForm.get('myFormNameDrop').get('myName').valueChanges.pipe(      
  debounceTime(400),
  distinctUntilChanged(),            
  filter((myName) => myName.length > 0),
  switchMap(myName => this.shoesService.details(myName)),
  shareReplay(1)
);

change this line :

this.results = this.myForm.value.myFormNameDrop.valueChanges.pipe( ...

to :

this.results = this.myForm.controls.myFormNameDrop.valueChanges.pipe( ...

this.myForm.controls['myFormNameDrop']

在模板中工作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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