Skip to content

Instantly share code, notes, and snippets.

@dancornilov
Created March 26, 2019 10:34
Show Gist options
  • Save dancornilov/4607baecadfda665888c5d939c18b59d to your computer and use it in GitHub Desktop.
Save dancornilov/4607baecadfda665888c5d939c18b59d to your computer and use it in GitHub Desktop.
Validator v2
import { Component, Input, OnInit } from '@angular/core';
import { FormControl, FormGroup, ValidationErrors } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-validator',
templateUrl: './validator.component.html',
styleUrls: ['./validator.component.scss']
})
export class ValidatorComponent implements OnInit {
@Input() public control: FormControl;
@Input() public customName: string;
public name: string;
constructor(private translateService: TranslateService) {
}
public ngOnInit(): void {
const fieldName = this.customName ? this.customName : this.getControlName();
this.name = this.translateService.instant(`fields.${fieldName}`);
}
/**
* Extract control name from formGroup
*
* @return string
*/
public getControlName(): string {
let controlName = null;
const parent = this.control['parent'];
if (parent instanceof FormGroup) {
for (const name in parent.controls) {
if (this.control === parent.controls[name]) {
controlName = name;
}
}
}
return controlName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment