Angular 2 Checkbox Dwukierunkowe Wiązanie Danych
Jestem całkiem nowy w Angular2 i mam mały problem:
W moim Login-Component-HTML, mam dwa checkboxy, które chcę powiązać w dwojaki sposób dane-powiązanie z Login-Component-TypeScript.
To jest HTML:
<div class="checkbox">
<label>
<input #saveUsername [(ngModel)]="saveUsername.selected" type="checkbox" data-toggle="toggle">Benutername speichern
</label
></div>
I to jest element.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;
// Hole Usernamen aus Local Storage falls gespeichert werden soll
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']);
}
Jeśli kliknę pole wyboru, otrzymam poprawną wartość w kontrolerze (komponencie).
Ale jeśli zmienię wartość na przykład saveUsername
w komponencie, pole wyboru nie "dostać" nową wartość.
Więc nie mogę manipulować pole wyboru z komponentu (tak jak chcę zrobić w ngOnInit
w komponencie.
Dzięki za pomoc!
9 answers
Możesz usunąć .selected
z saveUsername
w polu wyboru, ponieważ saveUsername jest wartością logiczną. zamiast [(ngModel)]
Użyj [checked]="saveUsername" (change)="saveUsername = !saveUsername"
Edit: Poprawne Rozwiązanie:
<input type="checkbox" [checked]="saveUsername" (change)="saveUsername = !saveUsername" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-24 11:51:44
Niestety rozwiązanie dostarczone przez @ hakani nie jest wiązaniem dwukierunkowym . Obsługuje tylko jednokierunkowy Model zmiany z części UI / FrontEnd.
Zamiast prostego:
<input [(ngModel)]="checkboxFlag" type="checkbox"/>
Zrobi dwukierunkowe Wiązanie dla checkbox.
Następnie, gdy Model checkboxFlag zostanie zmieniony z backendu lub części interfejsu - voila, checkboxFlag przechowuje rzeczywisty stan checkboxa.
Aby mieć pewność, że przygotowałem Kod Plunkera, aby przedstawić wynik : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk
Aby uzupełnić tę odpowiedź należy dodać import { FormsModule } from '@angular/forms'
do app.module.ts
i dodać do tablicy imports czyli
import { FormsModule } from '@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-30 09:04:55
Pracuję z Angular5 i musiałem dodać atrybut "name", aby Wiązanie działało... "Id" nie jest wymagane do wiązania.
<input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe">
Przekaż $event jako kolejny parametr i w funkcji możemy uzyskać dane wejściowe sprawdzane lub nie przez $ event.cel.sprawdzone
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-22 13:12:11
Wolę coś bardziej wyrazistego:
Komponent.html
<input #saveUserNameCheckBox
id="saveUserNameCheckBox"
type="checkbox"
[checked]="saveUsername"
(change)="onSaveUsernameChanged(saveUserNameCheckBox.checked)" />
Komponent.ts
public saveUsername:boolean;
public onSaveUsernameChanged(value:boolean){
this.saveUsername = value;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 11:58:50
Przy użyciu składni <abc [(bar)]="foo"/>
na angular.
To tłumaczy się na:
<abc [bar]="foo" (barChange)="foo = $event" />
Co oznacza, że Twój komponent powinien mieć:
@Input() bar;
@Output() barChange = new EventEmitter();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-21 20:04:01
Możesz użyć czegoś takiego, aby mieć dwukierunkowe powiązanie danych:
<input type="checkbox" [checked]="model.propertie" (change)="model.propertie = !model.consent_obtained_ind">
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-31 15:34:04
Aby uruchomić checkbox należy wykonać wszystkie poniższe kroki:
- Importuj
FormsModule
do swojego modułu - Umieść wejście wewnątrz znacznika
form
-
Twój wkład powinien wyglądać tak:
<input name="mpf" type="checkbox" [(ngModel)]="value" />
Uwaga: nie zapomnij wpisać nazwy w swoim wpisie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 22:11:14
Zrobiłem Niestandardowy komponent próbowałem dwukierunkowego wiązania
Mykomponent:
<input type="checkbox" [(ngModel)]="model" >
_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;
}
Strange thing is this works
<mycheckbox [checked]="isChecked" (checked)="isChecked = $event">
While this wont
<mycheckbox [(checked)]="isChecked">
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-13 16:31:14
Musisz dodać name="selected"
atrybut do input
elementu.
Na przykład:
<div class="checkbox">
<label>
<input name="selected" [(ngModel)]="saveUsername.selected" type="checkbox">Benutername speichern
</label>
</div>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 13:04:45