IT
Angular formGroup patchValue getRawValue 사용 예시
agnusdei1207
2023. 5. 18. 17:50
반응형
SMALL
adminForm = new FormGroup({
name: new FormControl<string>('', Validators.required),
tel: new FormControl<string>('', Validators.required),
id: new FormControl<string>('', Validators.required),
password: new FormControl<string>('', Validators.required),
passwordConfirm: new FormControl<string>('', Validators.required),
role: new FormControl<string>('', Validators.required),
updatedAt: new FormControl<Date>(new Date()),
});
constructor(private modalController: ModalController) {}
ngOnInit(): void {
const items = localStorage.getItem('admins');
if (this.id && items) {
let admins: Admin[] = JSON.parse(items);
const admin = admins.find((admin) => admin.id === this.id);
if (admin) {
this.adminForm.patchValue(admin); // 너무 편하죠?
}
}
}
submit() {
const item = this.adminForm.getRawValue(); // form value
const items = localStorage.getItem('admins');
if (items && item) {
let admins: Admin[] = JSON.parse(items);
const index = admins.findIndex((admin) => admin.id === item.id);
if (index !== -1) {
const body: Admin = {
id: item.id ?? '',
name: item.name ?? '',
password: item.password ?? '',
role: item.role as Role,
position: admins[index].position,
tel: item.tel ?? '',
createdAt: admins[index].createdAt,
updatedAt: item.updatedAt ?? new Date(),
};
admins[index] = body;
localStorage.setItem('admins', JSON.stringify(admins));
}
}
1. FormGroup 객체는 patchValue 메소드가 있습니다.
2. name 필드가 동일하면 자등으로 값읗 할당할 수 있습니다.
3. getRawValue 메소드는 해당 객체에 접근할 수 있습니다. adminForm.getRawValue()
4. value 값 하나하나에 접근할 떄 사용됩니다. adminForm.value
반응형
LIST