Search code examples
angularangular6angular-formsangular-pipe

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


Solution

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