Reputation: 223
given this component
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);
}
}
and its template:
<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>
What I'm trying to do is to get the form values when the checkbox changes its value. but right now it's not working as intended. The first time y click the checkbox I got
{feedback:0.5,mix:0.5,status:undefined,time:0.3}
and then
{status: true, feedback: 0.5, time: 0.3, mix: 0.5} when the checkbox is not checked
and
{status: false, feedback: 0.5, time: 0.3, mix: 0.5} when it's checked
Why is the form behavin like this?
Upvotes: 1
Views: 3400
Reputation: 50633
If you want to use NgModel
directive for data binding, you need to use ngModelChange
to pass data:
<input type="checkbox" name="status" [ngModel]="status" (ngModelChange)="switchEffect($event)" />
Then in your component:
switchEffect(event: any) {
console.log(event); // this will print current value of checkbox in console
}
Upvotes: 2
Reputation: 6854
It's because you are using one way binding. change to this:
<input type="checkbox" name="status" [(ngModel)]="status" (change)="switchEffect(f)" />
Upvotes: 0