Is it possible to get native element for formControl?

前端 未结 5 491
面向向阳花
面向向阳花 2020-12-03 09:36

I\'ve got Angular2 reactive form. I created formControls and assigned it to input fields by[formControl]=.... As I understand it creates nati

5条回答
  •  眼角桃花
    2020-12-03 10:27

    Yes, you have to write Directive with [formControl], [formControlName] selector. Full example:

    import { Directive, ElementRef } from "@angular/core";
    import { NgControl } from '@angular/forms';
    
    @Directive({
       selector: '[formControl], [formControlName]'
    })
    export class ControlErrorsDirective {
        get control() {
           return this.controlDir.control;
        }
    
        constructor(
            private controlDir: NgControl,
            private host: ElementRef) {
        }
        ngOnInit() {
            console.log(this.host.nativeElement);
        }
    }
    

    and in your html just use formControlName like this:

提交回复
热议问题