82 lines
2.1 KiB
TypeScript
82 lines
2.1 KiB
TypeScript
/* eslint-disable @typescript-eslint/explicit-function-return-type */
|
|
/* eslint-disable @typescript-eslint/member-ordering */
|
|
/* eslint-disable no-console */
|
|
import { CommonModule } from '@angular/common';
|
|
import { Component, OnInit } from '@angular/core';
|
|
import { FormGroup, Validators, FormArray, FormBuilder, ReactiveFormsModule } from '@angular/forms';
|
|
import { RouterModule } from '@angular/router';
|
|
import { DummyService } from './dummy.service';
|
|
|
|
export interface Item {
|
|
title: string;
|
|
completed: boolean;
|
|
priority: number;
|
|
}
|
|
|
|
@Component({
|
|
standalone: true,
|
|
selector: 'jhi-form-composer',
|
|
templateUrl: './form-composer.component.html',
|
|
styleUrls: ['./form-composer.component.scss'],
|
|
imports:[CommonModule, ReactiveFormsModule, RouterModule]
|
|
})
|
|
|
|
export class FormComposerComponent implements OnInit{
|
|
constructor(private serv: DummyService, private fb: FormBuilder) {}
|
|
prio = [0, 1, 2];
|
|
toDoListForm: FormGroup | any;
|
|
itemsList: Item[] = [];
|
|
|
|
defaultItem = {
|
|
title: '',
|
|
completed: false,
|
|
priority: null,
|
|
};
|
|
|
|
|
|
get itemsArray() {
|
|
return <FormArray>this.toDoListForm.get('items');
|
|
}
|
|
|
|
ngOnInit(): void {
|
|
this.toDoListForm = this.fb.group({
|
|
items: this.fb.array([]), //array di formControls
|
|
});
|
|
this.itemsList = this.serv.getMyData();
|
|
this.displayItems();
|
|
}
|
|
|
|
createItem(item: any) {
|
|
return this.fb.group({
|
|
title: [item.title, [Validators.required]],
|
|
completed: [item.completed, [Validators.required]],
|
|
priority: [item.priority, [Validators.required]],
|
|
});
|
|
}
|
|
|
|
addNewItem() {
|
|
const formGroup = this.createItem(this.defaultItem);
|
|
this.itemsArray.push(formGroup);
|
|
}
|
|
|
|
displayItems() {
|
|
const transformedItems = this.itemsList.map((item: any) =>
|
|
this.createItem(item) // per ogni item JSON costruisce un FormGroup
|
|
);
|
|
console.log(transformedItems);
|
|
this.toDoListForm.setControl('items', this.fb.array(transformedItems)) //assegno un formArray di FormGroup;
|
|
}
|
|
|
|
deleteItem(i: number) {
|
|
this.itemsArray.removeAt(i);
|
|
}
|
|
|
|
deleteAll() {
|
|
this.itemsArray.clear();
|
|
}
|
|
/*
|
|
track(item: any, index: number) {
|
|
return index;
|
|
}
|
|
*/
|
|
} |