-
Notifications
You must be signed in to change notification settings - Fork 79
/
product-quantity.component.ts
83 lines (72 loc) · 2.36 KB
/
product-quantity.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
ChangeDetectionStrategy,
Component,
Input,
OnChanges,
OnInit,
SimpleChange,
SimpleChanges,
} from '@angular/core';
import { FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { range } from 'lodash-es';
import { Product } from 'ish-core/models/product/product.model';
import { SelectOption } from 'ish-shared/forms/components/select/select.component';
import { SpecialValidators } from 'ish-shared/forms/validators/special-validators';
function generateSelectOptionsForRange(min: number, max: number): SelectOption[] {
return range(min, max)
.map(num => num.toString())
.map(num => ({ label: num, value: num }));
}
@Component({
selector: 'ish-product-quantity',
templateUrl: './product-quantity.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductQuantityComponent implements OnInit, OnChanges {
@Input() readOnly = false;
@Input() allowZeroQuantity = false;
@Input() quantityLabel = 'product.quantity.label';
@Input() product: Product;
@Input() parentForm: FormGroup;
@Input() controlName: string;
@Input() type?: 'select' | 'input';
@Input() class?: string;
quantityOptions: SelectOption[];
ngOnInit() {
this.parentForm.get(this.controlName).setValidators(this.getValidations());
}
get quantity() {
return this.parentForm.get(this.controlName) && this.parentForm.get(this.controlName).value;
}
get labelClass() {
return this.quantityLabel.trim() === '' ? 'col-0' : 'label-quantity col-6';
}
get inputClass() {
return this.quantityLabel.trim() === ''
? 'col-12' + (this.class ? this.class : '')
: 'col-6' + (this.class ? this.class : '');
}
getValidations(): ValidatorFn {
if (this.type !== 'select') {
return Validators.compose([
Validators.required,
Validators.min(this.allowZeroQuantity ? 0 : this.product.minOrderQuantity),
Validators.max(this.product.maxOrderQuantity),
SpecialValidators.integer,
]);
}
}
ngOnChanges(change: SimpleChanges) {
if (this.type === 'select') {
this.createSelectOptions(change.product);
}
}
private createSelectOptions(change: SimpleChange) {
if (change && change.currentValue) {
this.quantityOptions = generateSelectOptionsForRange(
this.product.minOrderQuantity,
this.product.maxOrderQuantity
);
}
}
}