角度指令中的输入属性

时间:2018-03-31 10:32:55

标签: html angular typescript

我的反应形式中使用的角度指令中的输入属性存在问题(这里的问题:在反应形式中使用指令是一种好习惯吗?)。我想为交叉字段验证创建通用指令,该指令将作为输入两个字符串,每个字符串用于要验证的字段的名称。这里有一些代码来说明我的意思。

// Directive
import { Directive, Input, OnInit } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';

@Directive({
    selector: '[appConfirmEqualValidator]',
    providers: [
        {
            provide: NG_VALIDATORS,
            useClass: ConfirmEqualValidatorDirective,
            multi: true,
        }
    ],
})
export class ConfirmEqualValidatorDirective implements OnInit, Validator {

    @Input() confEqSecControlName: string // = 'password' ; would work if uncommented
    @Input() confEqFirstControlName: string //  = 'confirmPassword' ;

    constructor() {
    }

    ngOnInit(): void {
    }

    validate(controlGroup: AbstractControl): { [key: string]: any; } {
        console.log(this.confEqFirstControlName + ' ' + this.confEqSecControlName);

        let firstControl = controlGroup.get(this.confEqFirstControlName);
        let secControl = controlGroup.get(this.confEqSecControlName);

        console.log(firstControl.value + ' fc ' + secControl.value + ' sec');
        if (firstControl && secControl && ( firstControl.value !== secControl.value )) {
            return { 'notEqual': true};
        } else {
            return null;
        }
    }

    registerOnValidatorChange?(fn: () => void): void {
        throw new Error("Method not implemented.");
    }
}


// HTML
<!-- Password Group -->
<div formGroupName="passwordGroup" appConfirmEqualValidator [confEqFirstControlName]="'password'" [confEqSecControlName]="'confirmPassword'">
    <!-- Password -->
    <div class="form-group">
        <label class="control-label" for="passwordId">Password</label>
        <div>
            <input class="form-control" formControlName="password" type="text" id="passwordId" placeholder="Password (required)" />
            <div class="text-danger" *ngIf="signUpForm.get('passwordGroup.password').errors">Danger</div>
        </div>
    </div>

    <!-- Confirm Password -->
    <div class="form-group">
        <label class="control-label" for="confirmPasswordId">Confirm Password</label>
        <div>
            <input class="form-control" formControlName="confirmPassword" type="text" id="confirmPasswordId" placeholder="Confirm Password (required)"/>
        </div>
    </div>
    <div class="text-danger" *ngIf="signUpForm.get('passwordGroup').errors?.notEqual">Not Equal</div>
</div>

pastebin for clarity

我是棱角分明但是从我在docs中读过的内容看起来应该很好。那不是。这些值根本没有绑定到属性,控制台记录'undefined'。当我指定默认值时,一切正常,但是对于硬编码值,我必须为每组字段制作一个指令/函数。我非常感谢你的帮助,谢谢。

0 个答案:

没有答案