Angular 4 - Accesarea elementelor HTML în Typescript folosind FormControlName


Vreau să accesez elementele HTML în TypeScript folosind FormControlName.

Pot să accesez elementul html folosind ID-ul elementelor

De exemplu :

var element = document.getElementById("txtID")

Dar putem accesa elementul folosind FormControl (fără a folosi ID-ul)

Răspuns #1

Folosește QuerySelector din HTML5.

Dacă eticheta ta de input html arată așa:

<input type="text" id="txtID" formControlName="txtID" />
var element = document.querySelector("input[formControlName='txtID']");

Răspunsul #2

Încercă soluția

HTML :

<h2>Using [formControl]</h2>
<input type="text" [formControl]="myControl"> {{ myControl.value }}
<button (click)="focusToFormControl()">Focus</button>

<hr>

<h2>Using formControlName</h2>
<form [formGroup]="myForm">
    <input type="text" formControlName="foo">
    <button (click)="focusToFormControlName('foo')">Focus</button>
</form>

TS :

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl,FormControlDirective, FormControlName, FormGroup } from '@angular/forms';


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

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  name = 'Angular 6';
  myControl = new FormControl();

  myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      foo: ''
    });
  }

  focusToFormControl() {
    (<any>this.myControl).nativeElement.focus();


  }

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