dimanche 4 novembre 2018

Angular 5 check box binding with formGroups

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" >
        
    </div>

</form>


Thanks in advance. Cheers




Aucun commentaire:

Enregistrer un commentaire