Is it possible to get native element for formControl?

前端 未结 5 509
面向向阳花
面向向阳花 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:02

    I can share one terrible solution but it works for me.

    In reactive forms we can use either

    1) FormControlDirective

    ts

    myControl = new FormControl('')
    

    template

    
    

    or

    2) FormControlName

    ts

    myForm: FormGroup;
    
    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {
      this.myForm = this.fb.group({
        foo: ''
      });
    }
    

    template

    So for these directives i could write some patch like

    1) FormControlDirective

    const originFormControlNgOnChanges = FormControlDirective.prototype.ngOnChanges;
    FormControlDirective.prototype.ngOnChanges = function() {
      this.form.nativeElement = this.valueAccessor._elementRef.nativeElement;
      return originFormControlNgOnChanges.apply(this, arguments);
    };
    

    2) FormControlName

    const originFormControlNameNgOnChanges = FormControlName.prototype.ngOnChanges;
    FormControlName.prototype.ngOnChanges = function() {
      const result =  originFormControlNameNgOnChanges.apply(this, arguments);
      this.control.nativeElement = this.valueAccessor._elementRef.nativeElement;
      return result;
    };
    

    After that we can easily access to native element having FormControl instance

    1) FormControlDirective

    focusToFormControl() {
      (this.myControl).nativeElement.focus();
    }
    

    2) FormControlName

    focusToFormControlName(name) {
      (this.myForm.get(name)).nativeElement.focus();
    }
    

    Plunker Example

提交回复
热议问题