How do I use formControlName if the attribute is in a nested formGroup?

I'm trying to set formControlName for a couple of radio buttons, but the problem is that the attribute I want to bind is inside a nested formgroup, and I get this error:

EXCEPTION: Uncaught (in promise): Error: Cannot find control with name: 'pubSub'

      

Template:

<div class="form-group">    
  <div>
     <label class="col-sm-2 control-label">
         Publicador/Subscriptor
     </label>
  </div>
  <div class="col-sm-3">
      <div class="radio c-radio">
          <label>
             <input formControlName="pubSub"
               type="radio" [value]="valoresPubSub.PUBLICADOR"/>
             <span class="fa fa-circle"></span>Publicador
          </label>
      </div>
      <div class="radio c-radio">
         <label>
            <input formControlName="pubSub"
              type="radio" [value]="valoresPubSub.SUBSCRIPTOR"/>
            <span class="fa fa-circle"></span>Subscriptor
          </label>
      </div>
   </div>
</div>

      

Group form in component:

constructor (private fb: FormBuilder){
}

ngOnInit() {
  this.formEnviarSolicitud = this.fb.group({
        accion: [null, Validators.required], 
        tipoModificacion: [null, Validators.required],
        webService: this.fb.group({
            pubSub: [null]
        })
    });
}

      

+3


source to share


1 answer


Solution: I need to use FormGroupName to bind DOM to FormGroup, then I can use formControlName to get the attribute names I want:

Template (notice the difference in the first line named formGroupName):



<div class="form-group" formGroupName="webService">    
  <div>
     <label class="col-sm-2 control-label">
         Publicador/Subscriptor
     </label>
  </div>
  <div class="col-sm-3">
      <div class="radio c-radio">
          <label>
             <input formControlName="pubSub"
               type="radio" [value]="valoresPubSub.PUBLICADOR"/>
             <span class="fa fa-circle"></span>Publicador
          </label>
      </div>
      <div class="radio c-radio">
         <label>
            <input formControlName="pubSub"
              type="radio" [value]="valoresPubSub.SUBSCRIPTOR"/>
            <span class="fa fa-circle"></span>Subscriptor
          </label>
      </div>
   </div>
</div>

      

Documentation for FormGroupName

+3


source







All Articles