openaire-library/dashboard/sharedComponents/input/input.component.ts

67 lines
2.1 KiB
TypeScript

import {Component, Input, OnDestroy, OnInit} from "@angular/core";
import {AbstractControl} from "@angular/forms";
import {HelperFunctions} from "../../../utils/HelperFunctions.class";
export interface Option {
icon?: string,
iconClass?: string,
value: any,
label: string
}
@Component({
selector: '[dashboard-input]',
template: `
<mat-form-field *ngIf="type != 'checkbox'" class="uk-width-1-1 uk-padding-remove">
<input *ngIf="type === 'text'" matInput [placeholder]="label"
[formControl]="formControl" [required]="required">
<textarea *ngIf="type === 'textarea'" [rows]="rows" matInput
[placeholder]="label" [formControl]="formControl" [required]="required"></textarea>
<mat-select *ngIf="type === 'select'" [placeholder]="label" [required]="required"
(openedChange)="stopPropagation()" [formControl]="formControl" [disableOptionCentering]="true">
<mat-option *ngFor="let option of options" [value]="option.value">
{{option.label}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-checkbox *ngIf="type === 'checkbox'" [formControl]="formControl" >{{label}}</mat-checkbox>
`
})
export class InputComponent implements OnInit, OnDestroy {
@Input('formInput') formControl: AbstractControl;
@Input('type') type: 'text' | 'textarea' | 'select' | 'checkbox' = 'text';
@Input('label') label: string;
@Input('rows') rows: number = 3;
@Input('options') options: Option[];
public required: boolean = false;
private initValue: any;
constructor() {
}
ngOnInit(): void {
this.initValue = HelperFunctions.copy(this.formControl.value);
if(this.formControl && this.formControl.validator) {
let validator = this.formControl.validator({} as AbstractControl);
this.required = (validator && validator.required);
}
this.formControl.valueChanges.subscribe(value => {
value = (value === '')?null:value;
if(this.initValue === value) {
this.formControl.markAsPristine();
}
});
}
ngOnDestroy(): void {
}
stopPropagation() {
if(event) {
event.stopPropagation();
}
}
}