How to create a reactive form in Angular

3

I have to implement some test in ionic, the questions for these test I collect them from the database and I show them. I have the problem when collecting the data.

To start I keep the data of the questions in a array of objects PreguntasTest that has the following attributes.

  id: string;
  tporden : number;
  testId: string;  
  tptexto_es: string
  tptexto_eu: string

This list is shown in Html along with radio with your answers.

<ion-content>
      <form (ngSubmit)="enviarRespuestas()" id="form_test"  >    
      <ion-list>
        <div >
          <div class="hilo" *ngFor="let preguntas of listaPreguntas; let i = index" >
            <div class="cabeceraTest" *ngIf="translate.currentLang=='es'" >          
                <h5>{{preguntas.tptexto_es}}          </h5>
            </div>
            <div class="cabeceraTest" *ngIf="translate.currentLang=='eu'" >          
              <h5> {{preguntas.tptexto_eu}}          </h5>
            </div>
            <div class="opciones" >
              <ion-input type="text" hidden="true" value={{preguntas.id}} name="id_pregunta" ></ion-input>
              <ion-list radio-group name="valor">
                <ion-item>
                  <ion-label>{{'test.si' | translate}}</ion-label>
                  <ion-radio value="1" ></ion-radio>
                </ion-item>
                <ion-item>
                  <ion-label>{{'test.no' | translate}}</ion-label>
                  <ion-radio value="0" ></ion-radio>
                </ion-item>
              </ion-list>
            </div>
          </div>

        </div>
      </ion-list>
  </form>

I have eliminated the tags of type formGroup or formGroupName since everything is giving me errors and / or does not collect the data in the right way.

My intention is to collect the data with the following structure:

respuestas{
  respuesta{
    id_pregunta:1,
    respuesta:0
  },
  respuesta{
    id_pregunta:2,
    respuesta:0
  },...
}

This is the component behind the html, it has a lot of garbage from the tests I've done, so a lot of the code is garbage.

@Component({
  selector: 'page-testPreguntas',
  templateUrl: 'test-preguntas.html'
})
export class TestPreguntasPage {  
  indice: number;
  listaPreguntas: PreguntasTest[];
  cargarMas: boolean; 
  test : Test;
  formulario : FormGroup;             
  constructor(public navCtrl: NavController, public navParams: NavParams,public menuCtrl: MenuController,
    public global: GlobalVars, public platform: Platform,  public translate: TranslateService, 
    public testService: TestService,private auth: AuthService,
    public formBuilder: FormBuilder
    ) {    
      this.formulario = this.formBuilder.group({
        questions: formBuilder.array([])     
      })
      platform.ready().then(() => {
        //para actualizar los colores del idioma
        global.actualizaIdioma();

        this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
            //cambiamos el idioma de los títulos de los temas
            this.cambiarLenguajeTitulo();
        });
    });
    this.test = navParams.get('test');
    this.cambiarLenguajeTitulo();
    this.indice = 0;
    this.cargarMas = false;
    this.cargarPreguntas()  
} 
/*private createMyForm(){  
  return this.formBuilder.group({

  })
}*/

  enviarRespuestas(){
    console.log("METODO ENVIAR RESPUESTAS");
    console.log(this.formulario.value)
    //console.log(this.formulario.controls[0].value);

  }

  cargarPreguntas(){
    // ESTE CODIGO RECOGE LOS DATOS DEL SERVER Y LOS GUARDA EN listaPreguntas
  }

  openMenu(){
    this.menuCtrl.open();
  }
  cambiarLenguajeTitulo(){    
    if(this.translate.currentLang=="es"){   
           this.test.titulo = this.test.tetitulo_es;
    }else{
        this.test.titulo = this.test.tetitulo_eu;
    }
  }

}
    
asked by Lombarda Arda 13.02.2018 в 12:20
source

1 answer

3

The problem you have in the component is all that code that you have been adding too much. The creation of the form could be something as simple as this:

First we create a FormArray :

let controls=listaPreguntas.map(() => ['',Validators.required]);
let formArray=this.formBuilder.array(controls);

With this you have already created a FormArray , with all the fields initialized as empty and all with a validator "required".

We put it in a FormGroup :

this.formulario = this.formBuilder.group({
  questions: formArray     
});

And that way you can generate the HTML:

<form [formGroup]="formulario">
  <div formArrayName="questions">
    <div class="hilo" *ngFor="let p of listaPreguntas; let i=index" >
      <div class="cabeceraTest">          
        <h5>{{p['tptexto_'+translate.currentLang]}} </h5>
      </div>

      <div class="opciones" >
        <ion-list radio-group [formControlName]="i" name="valor">
          <ion-item>
            <ion-label>{{'test.si' | translate}}</ion-label>
            <ion-radio value="1" ></ion-radio>
          </ion-item>
          <ion-item>
            <ion-label>{{'test.no' | translate}}</ion-label>
            <ion-radio value="0" ></ion-radio>
          </ion-item>
        </ion-list>
      </div>
    </div>
  </div>
</form>

I have never worked with Ionic, but I think that's the way it should be.

    
answered by 13.02.2018 / 15:23
source