각도 2 확인란 양방향 데이터 바인딩
나는 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
.
당신의 도움을 주셔서 감사합니다!
당신은 제거 할 수 있습니다 .selected
에서 saveUsername
saveUsername 부울이기 때문에 당신의 체크 박스를 입력한다. [(ngModel)]
사용 하는 대신[checked]="saveUsername" (change)="saveUsername = !saveUsername"
편집 : 올바른 해결책 :
<input
type="checkbox"
[checked]="saveUsername"
(change)="saveUsername = !saveUsername"/>
Update: Like @newman noticed when ngModel
is used in a form it won't work. However, you should use [ngModelOptions]
attribute like (tested in Angular 7):
<input
type="checkbox"
[(ngModel)]="saveUsername"
[ngModelOptions]="{standalone: true}"/> `
I also created an example at Stackblitz: https://stackblitz.com/edit/angular-abelrm
Unfortunately solution provided by @hakani is not two-way binding. It just handles One-way changing model from UI/FrontEnd part.
Instead the simple:
<input [(ngModel)]="checkboxFlag" type="checkbox"/>
will do two-way binding for checkbox.
Afterwards, when Model checkboxFlag is changed from Backend or UI part - voila, checkboxFlag stores actual checkbox state.
To be sure I've prepared Plunker code to present the result : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk
Just to complete this answer you should include the import { FormsModule } from '@angular/forms'
into app.module.ts
and add to imports array i.e
import { FormsModule } from '@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
I'm working with Angular5 and I had to add the "name" attribute to get the binding to work... The "id" is not required for binding.
<input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe">
I prefer something more explicit:
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;
}
When using <abc [(bar)]="foo"/>
syntax on angular.
This translates to: <abc [bar]="foo" (barChange)="foo = $event" />
Which means your component should have:
@Input() bar;
@Output() barChange = new EventEmitter();
You can just use something like this to have two way data binding:
<input type="checkbox" [checked]="model.property" (change)="model.property = !model.consent_obtained_ind">
To get checkbox work you should follow all these steps:
- import
FormsModule
in your module - Put the input inside a
form
tag your input should be like this:
<input name="mpf" type="checkbox" [(ngModel)]="value" />
Note: do not forget to put name in your input.
I have done a custom component tried two way binding
Mycomponent: <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">
You must add name="selected"
attribute to input
element.
For example:
<div class="checkbox">
<label>
<input name="selected" [(ngModel)]="saveUsername.selected" type="checkbox">Save username
</label>
</div>
In any situation, if you have to bind a value with a checkbox which is not boolean then you can try the below options
In the Html file:
<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>
in the componentischeckedWithOutBoolean: any = 'Y';
See in the stackblitz https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html
A workaround to achieve the same specially if you want to use checkbox with for loop is to store the state of the checkbox inside an array and change it based on the index of the *ngFor
loop. This way you can change the state of the checkbox in your component.
app.component.html
<div *ngFor="let item of items; index as 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;
}
}
My angular directive like 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">
참고URL : https://stackoverflow.com/questions/40214655/angular-2-checkbox-two-way-data-binding
'IT story' 카테고리의 다른 글
객체 문자열을 JSON으로 변환 (0) | 2020.06.03 |
---|---|
안드로이드 AlertDialog 단일 버튼 (0) | 2020.06.03 |
jQuery 트리거 파일 입력 (0) | 2020.06.03 |
Django에서 DateTimeField의 날짜를 어떻게 필터링합니까? (0) | 2020.06.03 |
AppSettings는 .config 파일에서 가치를 얻습니다. (0) | 2020.06.03 |