Skip to content

Instantly share code, notes, and snippets.

@vitaliel
Created January 13, 2023 12:47
Show Gist options
  • Save vitaliel/d4bcf65a8d5ede1b88e750ab841236cc to your computer and use it in GitHub Desktop.
Save vitaliel/d4bcf65a8d5ede1b88e750ab841236cc to your computer and use it in GitHub Desktop.
Angular password component
<div class="input-group">
<input [type]="fieldTextType ? 'text' : 'password'" class="form-control"
placeholder="Password"
[id]="formControlName"
[formControl]="control" />
<div class="input-group-append">
<span class="input-group-text">
<i
class="fa"
[ngClass]="{
'fa-eye-slash': !fieldTextType,
'fa-eye': fieldTextType
}"
(click)="toggleFieldTextType()"
></i>
</span>
</div>
</div>
import { Component, forwardRef, Injector, Input, ViewChild } from '@angular/core';
import { ControlContainer, ControlValueAccessor, FormControl, FormControlDirective,
NG_VALUE_ACCESSOR
} from '@angular/forms';
@Component({
selector: 'app-password-input',
templateUrl: './password-input.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => PasswordInputControl),
multi: true
}
]
})
export class PasswordInputControl implements ControlValueAccessor {
@ViewChild(FormControlDirective, { static: true }) formControlDirective: FormControlDirective;
@Input() formControlName = 'password';
@Input() placeholder = 'Password';
@Input() _value = '';
@Input() formControl: FormControl;
fieldTextType: boolean;
onChange: any = () => { };
onTouched: any = () => { };
constructor(
private injector: Injector
) { }
toggleFieldTextType() {
this.fieldTextType = !this.fieldTextType;
}
get control() {
return this.formControl || this.controlContainer?.control?.get(this.formControlName);
}
get controlContainer() {
return this.injector?.get(ControlContainer);
}
get value() {
return this._value;
}
set value(val) {
this._value = val;
this.onChange(val);
this.onTouched();
}
registerOnChange(fn) {
this.onChange = fn;
}
writeValue(value) {
if (value) {
this.value = value;
}
}
setDisabledState(isDisabled: boolean): void {
this.formControlDirective?.valueAccessor?.setDisabledState(isDisabled);
}
registerOnTouched(fn) {
this.onTouched = fn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment