Skip to content

Instantly share code, notes, and snippets.

@john182
Created January 29, 2018 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john182/e6f94c3fd632a188b0175018f88454f5 to your computer and use it in GitHub Desktop.
Save john182/e6f94c3fd632a188b0175018f88454f5 to your computer and use it in GitHub Desktop.
import { Component, OnInit, AfterContentInit, Input, forwardRef, ContentChild } from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, ControlValueAccessor } from '@angular/forms'
import { NgModel, FormControlName } from '@angular/forms'
@Component({
selector: 'app-campo-texto',
templateUrl: './campo-texto.component.html',
styles: [],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => CampoTextoComponent),
}
]
})
export class CampoTextoComponent implements OnInit, AfterContentInit, ControlValueAccessor {
@Input() classe: string;
@Input() requerido: string;
@Input() label: string;
@Input() tamanhoMaximo: 1;
tamanhoColuna = "form-group ";
innerValue: any;
onChange: any;
@ContentChild(NgModel) model: NgModel;
@ContentChild(FormControlName) control: FormControlName;
input: any
constructor() { }
ngOnInit() {
if (this.classe) {
this.tamanhoColuna += this.classe;
}
}
get value(): any {
return this.innerValue;
};
setValue(value: any) {
this.innerValue = value;
}
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
}
}
writeValue(obj: any): void {
this.innerValue = obj
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
}
setDisabledState?(isDisabled: boolean): void {
}
ngAfterContentInit() {
this.input = this.model || this.control;
console.log(this);
if (this.input === undefined) {
throw new Error('Esse componente precisa ser usado com uma diretiva ngModel ou formControlName')
}
}
hasError(): boolean {
return this.input.invalid && (this.input.dirty || this.input.touched)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment