首页 文章

在复选框更改时获取Angular2表单值

提问于
浏览
1

鉴于此组件

import { Component, Input, OnInit } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'effect',
    templateUrl: 'templates/effect.html'
})
export class EffectComponent implements OnInit {
    @Input() effect: any;
    constructor() { }
    ngOnInit() {
    }
    switchEffect(form) {
        console.log(form.value);
    }
}

及其模板:

<li class="collection-item">
    <form #f="ngForm">
        <div class="switch">
            <label>
                <input type="checkbox" name="status" [ngModel]="status" (change)="switchEffect(f)" />
                <span class="lever"></span>                    
            </label>    
        </div>
        <a (click)="switchSettings=!switchSettings">
        {{effect.publicName}}
            <i class="material-icons" [ngClass]="{'expand-less' : switchSettings}">expand_more</i>
        </a>
        <ul class="effect-settings collection" *ngIf="switchSettings">
            <li class="collection-item" *ngFor="let setting of effect.settings">
                <label>{{setting.type}}</label>
                <input type="range" name="{{setting.type}}" [ngModel]="setting.default" [value]="setting.default" [min]="setting.min" [max]="setting.max" step="0.1" />
            </li>
        </ul>
    </form>
</li>

我想要做的是在复选框更改其值时获取表单值 . 但是现在它没有按预期工作 . 第一次y点击我收到的复选框

{反馈:0.5,混合:0.5,状态:未定义,时间:0.3}

然后

{status:true,feedback:0.5,time:0.3,mix:0.5}未选中复选框时

检查时{status:false,feedback:0.5,time:0.3,mix:0.5}

为什么表单会像这样?

2 回答

  • 0

    如果要使用 NgModel 指令进行数据绑定,则需要使用 ngModelChange 来传递数据:

    <input type="checkbox" name="status" [ngModel]="status" (ngModelChange)="switchEffect($event)" />
    

    然后在你的组件中:

    switchEffect(event: any) {
        console.log(event); // this will print current value of checkbox in console
    }
    
  • 2

    这是因为你正在使用单向绑定 . 改为:

    <input type="checkbox" name="status" [(ngModel)]="status" (change)="switchEffect(f)" />
    

相关问题