0

我试图以角度形式显示字段的错误:

当我们在表单字段中进行更改并在控制台中打印它时,我能够得到错误,但我无法将其附加到 html 中:

app.component.html:

 <div class="form-group">
    <div class="col-sm-12">
              <label for="email" class="control-label">Email</label>
              <input type="text" id="email" class="form-control" formControlName="email" 
              validate
              [form_name] = "form"
              key = "email"
              >
     </div>
 </div>

这里 validate 是自定义指令,不,我想这样:

<div class="form-group">
    <div class="col-sm-12">
              <label for="email" class="control-label">Email</label>
              <input type="text" id="email" class="form-control" formControlName="email" 
              validate
              [form_name] = "form"
              key = "email"
              >
              <small class="invalid-feedback">Please Enter The Above Field</small>

     </div>
</div>

我的自定义指令文件是:

@Directive({
    selector: '[validate]',
    host: {"(input)": 'onInputChange($event)'}
})

export class fieldValidate{
    form_name;
    key;
    key_Error;
    count :number=0;
    message :string;
    @Input('form_name') 
    set _form_name(data :any){
        this.form_name =data;
    }

    @Input('key') 
    set _key(data :any){
        this.key=data;
    }
    @Output('err_msg') err_msg = new EventEmitter();

    Error_Messages ={
        'email' : " Format is invalid",
        'required' :" is Required",
        'maxlength' : " has Max Length"
    }



    constructor(
        private el :ElementRef,
        private renderer :Renderer2, 
        ){}


    onInputChange($event){
        if(this.form_name.get(this.key) instanceof FormControl){
            const controlErrors : ValidationErrors = this.form_name.get(this.key).errors;
            if(controlErrors != null){
                Object.keys(controlErrors).forEach(keyErrors=>{
                    console.log("Key is : " + this.key + " Key Error: " + keyErrors);
                    this.key_Error=keyErrors;
                })
            }
        }


        if(this.key_Error){
            this.renderer.addClass(this.el.nativeElement,"is-invalid");
            this.count++;
            console.log(this.key_Error + " "+this.count);
            this.message = <string> this.key;
            this.message = this.message + this.Error_Messages[this.key_Error];
            console.log(this.message);
            //this.err_msg.emit(this.message);


        }
        else {
            this.renderer.removeClass(this.el.nativeElement,"is-invalid");
        }
        this.key_Error=null;



    }
}

我想将 this.message 附加到上述输入字段。

4

0 回答 0