我对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中做的那样。

谢谢你的帮助!


当前回答

在Angular的p-复选框中,

使用p-复选框的所有属性

<p-checkbox name="checkbox" value="isAC" 
    label="All Colors" [(ngModel)]="selectedAllColors" 
    [ngModelOptions]="{standalone: true}" id="al" 
    binary="true">
</p-checkbox>

更重要的是,不要忘记包括[ngModelOptions]="{standalone: true}以及它挽救了我的一天。

其他回答

如果你想在for循环中使用复选框,有一种变通方法可以实现同样的效果,那就是将复选框的状态存储在数组中,并根据*ngFor循环的索引更改它。通过这种方式,您可以更改组件中复选框的状态。

app.component.html

<div *ngFor="let item of items; "索引为i"> <input type="checkbox" [checked]="category[i]" (change)="checkChange(i) "" > {{item.name}} < / div >

app.component.ts

items = [
    {'name':'salad'},
    {'name':'juice'},
    {'name':'dessert'},
    {'name':'combo'}
  ];

  category= []

  checkChange(i){
    if (this.category[i]){  
      this.category[i] = !this.category[i];
    }
    else{
      this.category[i] = true;
    }
  }

在Angular的p-复选框中,

使用p-复选框的所有属性

<p-checkbox name="checkbox" value="isAC" 
    label="All Colors" [(ngModel)]="selectedAllColors" 
    [ngModelOptions]="{standalone: true}" id="al" 
    binary="true">
</p-checkbox>

更重要的是,不要忘记包括[ngModelOptions]="{standalone: true}以及它挽救了我的一天。

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

正确答案:

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

更新:就像@newman注意到的,当ngModel在一个表单中使用时,它将不起作用。然而,你应该像这样使用[ngModelOptions]属性(在Angular 7中测试过):

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

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

我更喜欢更明确的说法:

component.html

<input #saveUserNameCheckBox
    id="saveUserNameCheckBox" 
    type="checkbox" 
    [checked]="saveUsername" 
    (change)="onSaveUsernameChanged(saveUserNameCheckBox.checked)" />

component.ts

public saveUsername:boolean;

public onSaveUsernameChanged(value:boolean){
    this.saveUsername = value;
}

在angular上使用<abc [(bar)]="foo"/>语法时。

这句话的意思是: <abc [bar]="foo" (barChange)="foo = $event" />

这意味着你的组件应该有:

@Input() bar;
@Output() barChange = new EventEmitter();