我是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組件中的值,則復選框不會“獲取”新值。因此,我無法從Component中操作復選框(就像我想在Component中的操作一樣)ngOnInit。
3 回答

叮當貓咪
TA貢獻1776條經驗 獲得超12個贊
我喜歡更明確的內容:
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;
}
添加回答
舉報
0/150
提交
取消