我对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: "9.0.0"
Angular CLI: 9.0.1
Node: 13.10.1
OS: linux x64

. html文件

<input [(ngModel)]="userConsent" id="userConsent" required type="checkbox"/> " I Accept"

.ts文件

userConsent: boolean = false;

其他回答

在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}以及它挽救了我的一天。

我正在使用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

我的angular指令像angularjs (ng-true-value ng-false-value)

@Directive({
    selector: 'input[type=checkbox][checkModel]'
})
export class checkboxDirective {
    @Input() checkModel:any;
    @Input() trueValue:any;
    @Input() falseValue:any;
    @Output() checkModelChange = new EventEmitter<any>();

    constructor(private el: ElementRef) { }

    ngOnInit() {
       this.el.nativeElement.checked = this.checkModel==this.trueValue;
    }

    @HostListener('change', ['$event']) onChange(event:any) {
        this.checkModel = event.target.checked ? this.trueValue : this.falseValue;
        this.checkModelChange.emit(this.checkModel);
    }

}

html

<input type="checkbox" [(checkModel)]="check" [trueValue]="1" [falseValue]="0">
Angular: "9.0.0"
Angular CLI: 9.0.1
Node: 13.10.1
OS: linux x64

. html文件

<input [(ngModel)]="userConsent" id="userConsent" required type="checkbox"/> " I Accept"

.ts文件

userConsent: boolean = false;