/
item.component.ts
129 lines (111 loc) · 2.75 KB
/
item.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import {
Component,
Input,
TemplateRef,
OnChanges,
ElementRef,
Renderer2,
ContentChild,
Host,
Optional,
AfterViewInit,
ChangeDetectorRef,
ChangeDetectionStrategy,
OnDestroy,
} from '@angular/core';
import { NgModel } from '@angular/forms';
import { updateHostClass, toNumber } from '@delon/util';
import { Subscription } from 'rxjs';
import { SHFWrapDirective } from './wrap.directive';
@Component({
selector: 'shf-item',
templateUrl: './item.component.html',
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SHFItemComponent implements OnChanges, AfterViewInit, OnDestroy {
private status$: Subscription;
@ContentChild(NgModel) private readonly ngModel: NgModel;
invalid = false;
// region: fields
@Input() tip: string;
_label = '';
_labelTpl: TemplateRef<any>;
@Input()
set label(value: string | TemplateRef<any>) {
if (value instanceof TemplateRef) {
this._label = null;
this._labelTpl = value;
} else {
this._label = value;
}
}
@Input()
set col(value: any) {
this._span = 24 / toNumber(value, 2);
}
get col() {
return this._span;
}
private _span: number;
@Input()
set labelWidth(value: any) {
this._labelWidth = toNumber(value, 0);
}
get labelWidth() {
return this._labelWidth;
}
private _labelWidth: number;
@Input() controlClass: string = '';
// endregion
private get isHorizontal(): boolean {
return !this.wrap || (this.wrap && this.wrap.nzLayout === 'horizontal');
}
constructor(
@Optional()
@Host()
private wrap: SHFWrapDirective,
private el: ElementRef,
private ren: Renderer2,
private cd: ChangeDetectorRef,
) {}
private fixLabelWidth(): this {
const w = this.wrap;
if (typeof this.col === 'undefined') {
this.col = w ? w.col : 2;
}
if (typeof this.labelWidth === 'undefined') {
this.labelWidth = w ? w.labelWidth : 100;
}
if (!this.isHorizontal) this._labelWidth = null;
return this;
}
setClassMap(): void {
const classMap = {
[`ant-form-item`]: true,
[`ant-col-${this.col}`]: this.isHorizontal,
[`ad-shf__item`]: true,
};
updateHostClass(this.el.nativeElement, this.ren, classMap);
this.cd.detectChanges();
}
ngOnChanges() {
this.fixLabelWidth().setClassMap();
}
ngAfterViewInit(): void {
this.fixLabelWidth().setClassMap();
if (this.ngModel) {
this.status$ = this.ngModel.statusChanges.subscribe(res => {
const status = res !== 'VALID';
if (this.invalid === status) return;
this.invalid = status;
this.cd.detectChanges();
});
}
}
ngOnDestroy(): void {
if (this.status$) {
this.status$.unsubscribe();
}
}
}