Skip to content

Instantly share code, notes, and snippets.

@qdouble
Last active August 25, 2016 15:17
Show Gist options
  • Save qdouble/a533dd7aa8fc2c94218236385b5a7829 to your computer and use it in GitHub Desktop.
Save qdouble/a533dd7aa8fc2c94218236385b5a7829 to your computer and use it in GitHub Desktop.
text-input
<md-input
align="start"
[dividerColor]="dynamicControl.valid || (!dynamicControl.valid && dynamicControl.errors?.required) ? 'primary' : 'warn'"
floatingPlaceholder="true"
[placeholder]="(dynamicControl.errors?.required && !hideRequired) ? label + ' (required)' : label "
[formControl]="dynamicControl"
[hintLabel]="help">
</md-input>
<button *ngIf="submit" type="submit" [disabled]="!form.valid">{{submit}}</button>
import { ChangeDetectionStrategy, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'text-input',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: TextInput, multi: true }
],
templateUrl: './text-input.html'
})
export class TextInput implements ControlValueAccessor, OnDestroy, OnInit {
@Input() error: string;
@Input() help: string;
@Input() hideErr: boolean;
@Input() hideRequired: boolean;
@Input() label: string = '';
@Input() submit: string;
controlSub: Subscription;
dynamicControl = new FormControl();
errorMessage: string;
ngOnInit() {
this.errorMessage = this.error || this.label + ' is invalid';
}
writeValue(value: any) {
this.dynamicControl.setValue(value);
}
registerOnChange(fn: (value: any) => void) {
this.controlSub = this.dynamicControl.valueChanges.subscribe(fn);
}
registerOnTouched() { }
ngOnDestroy() {
if (this.controlSub) this.controlSub.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment