Skip to content

Instantly share code, notes, and snippets.

@aarmora aarmora/Input module
Last active Sep 7, 2016

Embed
What would you like to do?
import {
Component,
NgModule,
Input,
Output,
EventEmitter,
forwardRef,
ModuleWithProviders
} from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormsModule, ReactiveFormsModule } from '@angular/forms';
const noop = () => {};
let nextId = 0;
export const CS_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CsInputComponent),
multi: true
};
@Component({
selector: 'cs-input',
styles: [require('./input.scss')],
providers: [CS_INPUT_CONTROL_VALUE_ACCESSOR],
host: {
'[class.focused-container]': 'isFocused',
'[class.invalid-input]': 'invalid'
},
template: require('./input.html')
})
export class CsInputComponent implements ControlValueAccessor {
private _value: any = '';
/** Callback registered via registerOnTouched (ControlValueAccessor) */
private _onTouchedCallback: () => void = noop;
/** Callback registered via registerOnChange (ControlValueAccessor) */
private _onChangeCallback: (_: any) => void = noop;
@Input() public type = 'text';
@Input() public placeholder = null;
@Input() public name: string = null;
@Input() public id: string = `cs-input-${nextId}`;
@Input() public required: boolean = false;
@Input() public invalid: boolean = false;
@Input() public tabIndex: number = 0;
@Input() public label: string = null;
get value(): any { return this._value; };
@Input() set value(v: any) {
v = this._convertValueForInputType(v);
if (v !== this._value) {
this.writeValue(v);
}
}
@Output() public focus: EventEmitter<Event> = new EventEmitter<Event>();
@Output() public blur: EventEmitter<Event> = new EventEmitter<Event>();
public writeValue(value: any) {
this._value = value;
this._onChangeCallback(value);
}
public registerOnChange(fn: any) {
this._onChangeCallback = fn;
}
public registerOnTouched(fn: any) {
this._onTouchedCallback = fn;
}
private _convertValueForInputType(v: any): any {
switch (this.type) {
case 'number': return parseFloat(v);
default: return v;
}
}
};
@NgModule({
imports: [
ReactiveFormsModule,
FormsModule
],
exports: [
CsInputComponent
],
declarations: [
CsInputComponent
]
})
export class CsInputModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: CsInputModule,
providers: []
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.