给出这个组件
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,反馈:0.5,时间:0.3,混合:0.5}未选中复选框时
和
{status:false,反馈:0.5,时间:0.3,混合:0.5},当它被检查时
为什么表单会像这样?
答案 0 :(得分:2)
如果要使用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
}
答案 1 :(得分:0)
这是因为您正在使用单向绑定。改为:
<input type="checkbox" name="status" [(ngModel)]="status" (change)="switchEffect(f)" />