2

I want to access HTML elements in typescript using FormcontrolName.

I can able to access html element using ID of elements

For example :

var element = document.getElementById("txtID")

But can we access the element using FormControl (without use of ID)

1
  • What have you tried so far to achieve this? Commented Jul 9, 2018 at 7:33

2 Answers 2

9

Use QuerySelector of HTML5.

If your html input tag is like this:

<input type="text" id="txtID" formControlName="txtID" />
var element = document.querySelector("input[formControlName='txtID']");
Sign up to request clarification or add additional context in comments.

3 Comments

Here you have mention selector name . but i don't want to mention it. is it possible?
Yes you can remove id attribute
var element = document.querySelector("[formControlName='txtID']"); this is not working.
0

Try Solution

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();
  }
}

2 Comments

Thanx for your reply. Code is not working . Is it neecessary to use focus while using nativeelement
sorry for inconvenience please refer update code i have give wrong url by mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.