首页 > 解决方案 > 如何将模糊功能传递和应用到父组件上的特定输入?

问题描述

我正在使用自定义输入字段作为单独的组件。我通过指令在父组件中添加了多个输入字段:<app-input ...></app-input>

我想将模糊事件/函数传递给父组件以进行特定输入(在本例中为密码字段),以获取其值并根据 Reg 表达式检查该值。

我已经搜索了很长时间(也在 SO 上)并尝试了几个选项,但它们都没有给出预期的干净行为。

我不断收到以下错误:

el => 未定义

我认为关键是如何将确切的元素 Ref 传递给,form.component.html以便该函数可以应用于password在这种情况下的确切特定输入字段。

我在用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 toogleRegExCheck = false;
    ...

    constructor() {
        this.password_regExp = '......';
    }

    ngOnInit() {
    }

    public onBlur(el) {
        console.log(`el => ${el}`);
        if (!password_regExp.test(el)) {
           this.toogleRegExCheck = true; 
        } else {
           this.toogleRegExCheck = false;
        }
    }
}

标签: javascriptangulartypescript

解决方案


通过Event

 (onFieldBlur)="onBlur($event)"> . 

推荐阅读