我对Angular2很陌生,我有一个小问题:

在我的Login-Component-HTML中,我有两个复选框,我想以两种数据绑定的方式绑定到Login-Component-TypeScript。

这是HTML:

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

这是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']);
    }

如果我单击复选框,我将在控制器(组件)中获得正确的值。

但是,如果我在组件中更改了例如saveUsername的值,复选框就不会“获得”新值。

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

谢谢你的帮助!


当前回答

在任何情况下,如果你必须绑定一个非布尔值的复选框,那么你可以尝试下面的选项

在Html文件中:

<div class="checkbox">
<label for="favorite-animal">Without boolean Value</label>
<input type="checkbox" value="" [checked]="ischeckedWithOutBoolean == 'Y'" 
(change)="ischeckedWithOutBoolean = $event.target.checked ? 'Y': 'N'">
</div>

在componentischeckedWithOutBoolean: any = 'Y';

在斯塔克布利茨 https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html

其他回答

不幸的是,@hakani提供的解决方案不是双向绑定。它只处理从UI/FrontEnd部分单向更改模型。

而是简单的:

<input [(ngModel)]="checkboxFlag" type="checkbox"/>

将为复选框做双向绑定。

之后,当模型checkboxFlag从后端或UI部分更改时——瞧,checkboxFlag存储实际的复选框状态。

为了确保我已经准备了Plunker代码来显示结果:https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk

为了完成这个回答,你应该把import {FormsModule}从'@angular/forms'包含到app.module.ts中,并添加到imports数组中

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

我正在使用Angular5,我必须添加"name"属性来让绑定工作…绑定时不需要“id”。

<input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe">

在任何情况下,如果你必须绑定一个非布尔值的复选框,那么你可以尝试下面的选项

在Html文件中:

<div class="checkbox">
<label for="favorite-animal">Without boolean Value</label>
<input type="checkbox" value="" [checked]="ischeckedWithOutBoolean == 'Y'" 
(change)="ischeckedWithOutBoolean = $event.target.checked ? 'Y': 'N'">
</div>

在componentischeckedWithOutBoolean: any = 'Y';

在斯塔克布利茨 https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html

我已经做了一个自定义组件尝试双向绑定

Mycomponent: <输入类型=“checkbox”[(ngModel)]=“模型”>

_model:  boolean;   

@Output() checked: EventEmitter<boolean> = new EventEmitter<boolean>();

@Input('checked')
set model(checked: boolean) {

  this._model = checked;
  this.checked.emit(this._model);
  console.log('@Input(setmodel'+checked);
}

get model() {
  return this._model;
}

奇怪的是,这种方法奏效了

<mycheckbox  [checked]="isChecked" (checked)="isChecked = $event">

虽然这不会

<mycheckbox  [(checked)]="isChecked">

我知道这可能是重复的答案 但是对于任何一个想要加载带有selectall复选框的复选框列表的人来说,我遵循这个例子: 使用angular 2+选中所有/取消选中所有复选框

它工作得很好,只是需要添加

[ngModelOptions]="{standalone: true}" 

最终的HTML应该是这样的:

<ul>
    <li><input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/></li>
    <li *ngFor="let n of names">
    <input type="checkbox" [(ngModel)]="n.selected" (change)="checkIfAllSelected();">{{n.name}}
    </li>
  </ul>

打印稿

  selectAll() {
    for (var i = 0; i < this.names.length; i++) {
      this.names[i].selected = this.selectedAll;
    }
  }
  checkIfAllSelected() {
    this.selectedAll = this.names.every(function(item:any) {
        return item.selected == true;
      })
  }

希望这对你有所帮助 非常感谢