Junias Junias - 4 months ago 256
TypeScript Question

Angular 2 Checkbox Two Way Data Binding

I´m fairly new to Angular2 and i have a little problem:
In my Login-Component-HTML I have two checkboxes, which i want to bind in two way data-binding to the Login-Component-TypeScript.
This is the HTML:

<div class="checkbox">
<input #saveUsername [(ngModel)]="saveUsername.selected" type="checkbox" data-toggle="toggle">Benutername speichern

And this is the Component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Variables } from '../../services/variables';

selector: 'login',
moduleId: module.id,
templateUrl: 'login.component.html',
styleUrls: ['login.component.css']

export class LoginComponent implements OnInit {

private saveUsername: boolean = true;
private autoLogin: boolean = true;
constructor(private router: Router, private variables: Variables) { }

ngOnInit() {
this.loginValid = false;
// Hole Usernamen aus Local Storage falls gespeichert werden soll
if (window.localStorage.getItem("username") === null) {
this.saveUsername = true;
this.autoLogin = true;
console.log(this.saveUsername, this.autoLogin);
} else {
console.log("init", window.localStorage.getItem("username"));

login(username: string, password: string, saveUsername: boolean, autoLogin: boolean) {
console.log(saveUsername, autoLogin);

If I click an checkbox, i get the correct value in the controller (component).
But if I change the value of for example
in the component, the checkbox didn´t "get" the new value.
So i can´t manipulate the checkbox from the Component (like I want to do in the
in the component.

Thanks for your help!


you can remove .selected from saveUsername in your checkbox input since saveUsername is a boolean. instead of [(ngModel)] use [checked]="saveUsername" (change)="saveUsername = !saveUsername"

Edit: Correct Solution:

<input type="checkbox" [checked]="saveUsername" (change)="saveUsername = !saveUsername" />