I have created a custom input field as a separate component. I want to include multiple input fields in the parent component using directives:
<app-input ...></app-input>
My goal is to pass the blur event/function to the parent component specifically for the password field, so that I can retrieve its value and validate it based on a RegEx pattern.
I have spent quite some time searching (including on SO) and trying various options, but none of them provided the desired clean behavior.
Continuously receiving the error message:
el => undefined
The challenge seems to be how to pass the exact element Ref to form.component.html
so that the function can be executed on the specific input field which happens to be the password
field in this case.
Using Angular: 5.2.10
input.component.html:
<mat-form-field>
<mat-label>
<mat-icon matPrefix>lock</mat-icon>
<span>{{ inputLabel }}</span>
</mat-label>
<input matInput type="{{inputType}}" name="{{inputName}}" [(ngModel)]="model" (ngModelChange)="modelChange.next($event)" required="{{required}}" pattern="{{regEx}}" (blur)="onFieldBlurClient('name.value')">
<mat-error align="end">
{{ inputError }}
</mat-error>
</mat-form-field>
input.component.ts:
export class InputComponent implements OnInit {
public parentFormGroup: FormGroup;
@Output() onFieldBlur: EventEmitter<any> = new EventEmitter<any>();
@Input('label') inputLabel: string;
@Input('name') inputName: string;
@Input('validationError') inputError: string;
@Input('type') inputType: string;
@Input('pattern') regEx: string;
@Input() required = true;
@Input() model: any;
@Output() modelChange = new EventEmitter();
constructor() {
}
ngOnInit() {
}
onFieldBlurClient(el) {
this.onFieldBlur.emit(true);
}
}
form.component.html:
<app-input [label]="'Password'"
[type]="'password'" [name]="'password'"
[validationError]="'Pass is not valid'"
[required]="true"
[parentFormGroup]="form"
[pattern]="(password_rexExp)" (onFieldBlur)="onBlur()"> .
</app-input>
form.component.ts:
export class FormComponent implements OnInit {
....
public password_regExp
public toggleRegExCheck = false;
...
constructor() {
this.password_regExp = '......';
}
ngOnInit() {
}
public onBlur(el) {
console.log(`el => ${el}`);
if (!password_regExp.test(el)) {
this.toggleRegExCheck = true;
} else {
this.toggleRegExCheck = false;
}
}
}