Angular 2 Checkbox 双向数据绑定 - Angular 2 Checkbox Two Way Data Binding

问题:

I´m fairly new to Angular2 and I have a little problem:我对 Angular2 还很陌生,我有一个小问题:

In my Login-Component-HTML, I have two checkboxes, which I want to bind in two way data-binding to the Login-Component-TypeScript.在我的 Login-Component-HTML 中,我有两个复选框,我想以两种方式将它们绑定到 Login-Component-TypeScript。

This is the HTML:这是 HTML:

<div class="checkbox">
<label>
    <input #saveUsername [(ngModel)]="saveUsername.selected" type="checkbox" data-toggle="toggle">Save username
</label>
</div>

And this is the Component.ts:这是 Component.ts:

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

@Component({
    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;
        // Get user name from local storage if you want to save

        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) {
        this.variables.setUsername(username);
        this.variables.setPassword(password);
        this.variables.setIsLoggedIn(true);
        console.log(saveUsername, autoLogin);
        //this.router.navigate(['dashboard']);
    }

If I click an checkbox, I get the correct value in the controller (component).如果我单击一个复选框,我会在控制器(组件)中获得正确的值。

But if I change the value of for example saveUsername in the component, the checkbox didn't "get" the new value.但是,如果我更改组件中例如saveUsername的值,则复选框不会“获取”新值。

So I can´t manipulate the checkbox from the Component (like I want to do in the ngOnInit in the component.所以我不能从组件中操作复选框(就像我想在组件中的ngOnInit中做的ngOnInit

Thanks for your help!感谢您的帮助!


解决方案:

参考一: https://en.stackoom.com/question/2ijfT
参考二: https://stackoom.com/question/2ijfT
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章