0

I cannot seem to get 2 way binding to work with formGroups

my objective; to have checkboxes that add or remove items form an array that will be stored...and if the model has the item the form should pre-check.

I am getting an error :

Error:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:

Frustrated and need help!

StackBitz is acting a bit weird not rendeing labels - but it may be because of the error.

https://stackblitz.com/edit/angular-bfkaa4

COMPONENT:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

import { MyClassesModel } from './myClasses.model';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

    classesList: string[];
    selectedClasses: string[];  
    form: FormGroup;
    model = new MyClassesModel({});
    loading = false;

    constructor( ) { }

    formDisabled () {
        return this.loading === true;
    }

    formModel () {
        return {
            myClasses: this.form.get('myClasses').value,
        };
    }

    ngOnInit() { 
        this.selectedClasses = [];
        this.classesList = [
            'English',
            'Spanish',
            'Italian',
        ];

        this.form = new FormGroup({
            myClasses: new FormControl({
                value: this.selectedClasses,
                disabled: this.formDisabled,
            })
        });

    }

  checkClasses(e) { 
    console.log(e.value);

  }
  submitForm() {}

}

FORM:

    <form  novalidate="novalidate"
        autocomplete="off"
        [formGroup]="form"
        (ngSubmit)="submitForm()" >

    <label>My Classes:</label>
    <div *ngFor="let name of classesList">
        <input type="checkbox" 
            name="myClasses[]"
            [(ngModel)]="myClasses"
            (change)="checkClasses($event)"
            [value]="name" >
        {{name}}
    </div>

</form>
{{form.value|json}}

Thanks in advance. Cheers

j-p
  • 3,698
  • 9
  • 50
  • 93
  • Are you attempting to use [Reactive Forms](https://angular.io/guide/reactive-forms) or [Template-driven Forms](https://angular.io/guide/forms)? The error is indicating your are attempting to use Reactive Forms, but haven't provided a `formControlName` for a `FormControl` registered in `FormGroup`. You're mixing reactive/template forms. Given you have are using `*ngFor` to render potentially multiple checkboxes, you should consider reviewing/using [Form Array](https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays) to render and bind multiple checkboxes to a `FormGroup`. – Alexander Staroselsky Nov 05 '18 at 04:43
  • Check this: https://stackblitz.com/edit/angular-ydqfmm – Chellappan வ Nov 05 '18 at 04:44
  • Possible duplicate of [Angular ReactiveForms: Producing an array of checkbox values?](https://stackoverflow.com/questions/40927167/angular-reactiveforms-producing-an-array-of-checkbox-values) – Alexander Staroselsky Nov 05 '18 at 04:46
  • @AlexanderStaroselsky - I confess to being overwhelmed by the 'options', I thought I was using reactive forms, but obviously some things don't mix and match. I am looking at your suggestion. – j-p Nov 05 '18 at 04:50
  • @Chellappan - your example displays disabled checkboxes, thx, while the checkboxes all show and no errors - I cannot check boxes...it does not work. – j-p Nov 05 '18 at 04:51
  • if you set disabled: false then your check box will enabled – Chellappan வ Nov 05 '18 at 04:53
  • @Chellappan - ok, but then the checkboxes just toggle true false, they dont add to the array – j-p Nov 05 '18 at 05:14
  • use formArray :https://stackblitz.com/edit/angular-ydqfmm – Chellappan வ Nov 05 '18 at 05:25
  • @Chellappan -Thank you so much for helping - I see what you did, and I was experimenting with formarray - however I want the array to be text, not true false. my data to store will be ['english','italian'] not [true,false,true] - any help? – j-p Nov 05 '18 at 05:50
  • i have updated the stackblitz check the console – Chellappan வ Nov 05 '18 at 05:58
  • @Chellappan - thx - if you move your answer to an answer (not a comment) I'll mark it correct and give it a + – j-p Nov 05 '18 at 06:21
  • UGH - I may be totally missing something here - but the way you wrote your code to subscribe to any form changes, cause a 'loop' when I try to assign the value of "selectedItems" to a form field - so I can submit it. That array of text does me no good sitting in a vairable - if I cannot pass it in the form. I hope I make sense... – j-p Nov 05 '18 at 06:38

0 Answers0