blob: 921c923dfbe39357eefa6e0f3a47a0e86a25c5d4 [file] [log] [blame]
Sonsino, Ofir (os0695)ff76b5e2018-07-10 15:57:37 +03001import {Component, Input, OnInit} from '@angular/core';
2import {FormControl, FormGroup, Validators} from "@angular/forms";
3import {DynamicInput, DynamicMultiSelect, DynamicNumber, DynamicSelect} from "../../shared/models/dynamicInput";
4
5@Component({
6 selector: 'dynamic-inputs',
7 templateUrl: './dynamic-inputs.html',
8 styleUrls: ['./dynamic-inputs.scss']
9})
10
11export class DynamicInputsComponent implements OnInit{
12 @Input() public list:any[] = [];
13 @Input() public group: FormGroup;
14
15 private dynamicList:DynamicInput<any>[] = [];
16
17 isDynamicNumber(item: any): item is DynamicNumber {
18 return item;
19 }
20
21 buildValidators(item: DynamicInput<any>) {
22 let validatorArr = [];
23 item.maxLength && validatorArr.push(Validators.maxLength(item.maxLength));
24 item.minLength && validatorArr.push(Validators.minLength(item.minLength));
25 if(this.isDynamicNumber(item)) {
26 item.max && validatorArr.push(Validators.max(item.max));
27 item.min && validatorArr.push(Validators.min(item.min));
28 }
29 return Validators.compose(validatorArr);
30 }
31
32 ngOnInit(): void {
33 this.list.forEach((item)=> {
34 let dynamicItem: DynamicInput<any>;
35 switch (item.type) {
36 case 'multi_select':
37 item.optionList.forEach(function(option) { option.id = option.id||option.name;
38 option.itemName = option.name;});
39 item.settings = {
40 disabled: !item.isEnabled,
41 text: item.prompt,
42 };
43 dynamicItem = new DynamicMultiSelect(item);
44 break;
45 case 'select':
46 let defaultValue:any = item.optionList.find((option) => option.isDataLoading && option.name);
47 item.value = defaultValue && defaultValue.id;
48 dynamicItem = new DynamicSelect(item);
49 break;
50 case 'boolean':
51 item.value = item.value || false;
52 item.optionList = [{name: true, isPermitted: true, isDataLoading: item.value}, {name: false, isPermitted: true, isDataLoading: !item.value}];
53
54 dynamicItem = new DynamicSelect(item);
55 break;
56 case 'number':
57 dynamicItem = new DynamicNumber(item);
58 break;
59 case 'file':
60 dynamicItem = new DynamicInput<any>(item);
61 break;
62 case 'checkbox':
63 dynamicItem = new DynamicInput<boolean>(item);
64 break;
65 case 'map':
66 item.prompt = "{<key1>: <value1>,\.\.\.,<keyN>: <valueN>}";
67 dynamicItem = new DynamicInput<string>(item);
68 break;
69 case 'list':
70 item.prompt = "[<value1>,...,<valueN>]";
71 dynamicItem = new DynamicInput<string>(item);
72 break;
73 default: dynamicItem = new DynamicInput<string>(item);
74 }
75 this.dynamicList.push(dynamicItem);
76 this.group.addControl(dynamicItem.name, new FormControl({value: dynamicItem.value, disabled: !dynamicItem.isEnabled}, this.buildValidators(dynamicItem)));
77 })
78 }
79
80}