代码之家  ›  专栏  ›  技术社区  ›  j-p

Angular 5复选框与formGroups绑定

  •  0
  • j-p  · 技术社区  · 6 年前

    我似乎无法使用表单组进行双向绑定

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

    沮丧需要帮助!

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

    组件:

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

    提前谢谢。 干杯

    0 回复  |  直到 6 年前