dimanche 17 février 2019

How to add checkbox dynamically to angular forms (Angular 4)

I'm working on angular 4 with Angular forms, how to dynamically add an input (checkbox) after building the form.

         signes_p = [
            { id: 'x1', name: 'bus' },
            { id: 'x2', name: 'car' }
         ];

         ngOnInit() {
          const controls = this.signes_p.map(c => new FormControl(false));
          this.form = this.fb.group({
            signes: new FormArray(controls),
          });
         }

        addSigne(){
          if(this.new_signe && this.new_signe.trim().length>0){

            this.signes_p.push({
              id: this.new_signe,
              name: this.new_signe.replace(/^\w/, c => c.toUpperCase())
            })
          const controls = this.signes_p.map(c => new FormControl(false));
          const control = <FormArray>this.form.controls['signes'];
          var x = this.fb.group(controls[controls.length-1])
          control.push(x);
         }
        }

                  <form [formGroup]="form" (ngSubmit)="onSubmit()">
                        <div class="form-group" >
                          <label for="signes" class="col-2 col-form-label" >Signes</label>  
                            <div class="custom-control custom-checkbox" formArrayName="signes" *ngFor="let signe of form.controls.signes.controls; let i = index">
                              <input type="checkbox" class="custom-control-input" [formControlName]="i" id="">
                              <label class="custom-control-label" for=""> </label>
                            </div>

                            <div class="row" style="margin-top:20px;">
                                <input class="form-control col-2" type="text" placeholder="Ajouter un autre..." [(ngModel)] = "new_signe" [ngModelOptions]="{standalone: true}" > 
                                <a class="btn btn-success btn-sm" style="color: white;margin-left: 10px;" (click)="addSigne()"><i class="fa fa-plus" aria-hidden="true"></i></a>
                            </div>        
                        </div>
                     ...
                    <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Enregistrer</button>   
                  </form>

i've also tried this example, it doesn't helped

medium_example

control.registerOnChange is not a function

Must supply a value for form control with name: 'validator'.




Aucun commentaire:

Enregistrer un commentaire