Angular 2 Checkbox 双向数据绑定 [英] Angular 2 Checkbox Two Way Data Binding

查看:94
本文介绍了Angular 2 Checkbox 双向数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular2 的新手,我有一个小问题:

在我的 Login-Component-HTML 中,我有两个复选框,我想以两种方式将它们绑定到 Login-Component-TypeScript.

这是 HTML:

<标签><input #saveUsername [(ngModel)]="saveUsername.selected" type="checkbox" data-toggle="toggle">保存用户名

这是 Component.ts:

import { Component, OnInit } from '@angular/core';从@angular/router"导入{路由器};从'../../services/variables'导入{变量};@成分({选择器:'登录',模块 ID:module.id,templateUrl: 'login.component.html',styleUrls: ['login.component.css']})导出类 LoginComponent 实现 OnInit {私人保存用户名:boolean = true;私人自动登录:boolean = true;构造函数(私有路由器:路由器,私有变量:变量){}ngOnInit() {this.loginValid = false;//如果要保存,则从本地存储中获取用户名if (window.localStorage.getItem("username") === null) {this.saveUsername = true;this.autoLogin = true;console.log(this.saveUsername, this.autoLogin);} 别的 {console.log("init", window.localStorage.getItem("username"));}}登录(用户名:字符串,密码:字符串,保存用户名:布尔值,自动登录:布尔值){this.variables.setUsername(username);this.variables.setPassword(密码);this.variables.setIsLoggedIn(true);控制台日志(保存用户名,自动登录);//this.router.navigate(['dashboard']);}

如果我点击一个复选框,我会在控制器(组件)中得到正确的值.

但是,如果我更改组件中例如 saveUsername 的值,复选框不会获取"新值.

所以我不能从组件操作复选框(就像我想在组件的 ngOnInit 中做的那样.

感谢您的帮助!

解决方案

您可以在复选框输入中从 saveUsername 中删除 .selected,因为 saveUsername 是一个布尔值.代替 [(ngModel)] 使用 [checked]="saveUsername" (change)="saveUsername = !saveUsername"

正确的解决方案:

<输入类型=复选框"[选中]="保存用户名"(change)="saveUsername = !saveUsername"/>

更新: 就像@newman 注意到在表单中使用 ngModel 时它不起作用一样.但是,您应该使用 [ngModelOptions] 属性,例如(在 Angular 7 中测试):

<输入类型=复选框"[(ngModel)]="saveUsername"[ngModelOptions]="{standalone: true}"/>`

我还在 Stackblitz 创建了一个示例:https://stackblitz.com/edit/angular-abelrm

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

And this is the 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.

So I can´t manipulate the checkbox from the Component (like I want to do in the ngOnInit 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"/>

Update: Like @newman noticed when ngModel is used in a form it won't work. However, you should use [ngModelOptions] attribute like (tested in Angular 7):

<input
  type="checkbox"
  [(ngModel)]="saveUsername"
  [ngModelOptions]="{standalone: true}"/> `

I also created an example at Stackblitz: https://stackblitz.com/edit/angular-abelrm

这篇关于Angular 2 Checkbox 双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆