Eneko de la Torre
Eneko de la Torre

Reputation: 155

How can 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'

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

The formGroup in the 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]
        })
    });
}

Upvotes: 3

Views: 1345

Answers (1)

Eneko de la Torre
Eneko de la Torre

Reputation: 155

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

The template (note the difference in the first line with 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

Upvotes: 3

Related Questions