Leveraging FormControlName in Typescript to Interact with HTML Components in Angular 4

How can I use FormControlName to access HTML elements in typescript?

Typically, I am able to access HTML elements using their ID. For example:

var element = document.getElementById("txtID")

But is it possible to access the element without using its ID and instead using FormControl?

Answer №1

Try incorporating QuerySelector from HTML5 into your code.

For example, if you have an html input tag set up like this:

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

Answer №2

Check out the Solution

HTML Code:

<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>

TypeScript Code:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with knockout view - unable to remove item from view after deletion

I'm facing an issue with my code that deletes an exam from a list of exams on a page, but the deleted exam still shows up until the page is manually refreshed. This pattern works correctly on other pages, so I don't understand why it's not w ...

Guide on how to automatically navigate to the homepage upon logging in using Angular

It's puzzling to see my navbar appearing on the login page as well. Another issue is that even after successfully logging in and receiving the token, I am not redirected to the homepage. Let me outline what I have tried so far - starting with my modul ...

Directive for displaying multiple rows in an Angular table using material design

I am attempting to create a dynamic datatable with expandable rows using mat-table from the material angular 2 framework. Each row has the capability of containing subrows. The data for my rows is structured as an object that may also include other sub-ob ...

Perform the subtraction operation on two boolean values using Typescript

I'm working with an array: main = [{ data: x, numberField: 1; }, { data: y, numberField: 2; }, { data: x, numberField: 3; }, { data: z, numberField: 4; }, { data: ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

Ionic - Smooth horizontal tab scrolling for sorted categories

Currently, we are developing a web/mobile application that includes horizontal scroll tabs to represent Categories. While this feature works well on mobile devices, it requires additional functionality for web browsers. Specifically, we need to add two arr ...

Substitute all properties of a specific type with a predetermined value in Typescript using recursive substitution

If we consider the given type structure: type Person = { name: string age: number experience: { length: number title: string } } Can we create a type like this: type FieldsOfPerson = { name: true age: true experience: { length: t ...

How to enable Autocomplete popper to expand beyond the menu boundaries in Material UI

Within my Menu component, I have an Autocomplete element. When the Autocomplete is clicked, the dropdown list/Popper appears but it's confined within the Menu parent. How can I make it so that the Autocomplete's dropdown list/Popper isn't re ...

How do I modify the local settings of the ngx-admin datepicker component to show a Turkish calendar view?

Looking for tips on customizing the new datepicker component in Nebular ngx-admin. Specifically, I want to change the local settings to display the calendar as Turkish. Explored the library but still seeking alternative methods. Any suggestions? ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...

Uncertainty surrounding the extent of a button's scope within an Angular application

(click) event in one instance of a component is causing the function in another instance to be triggered unexpectedly. I am having trouble describing this issue. For reference, I have included a working example on stackblitz. When clicking on both buttons ...

The Firebase Cloud Function is failing to trigger on the onCreate event within the Firebase Realtime Database

I recently deployed a function to Firebase with the following code: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; console.log('FILE LOADED'); const serviceAccount = require(' ...

The specified module could not be located in the ngx-toastr library

I'm having trouble finding the solution... ERROR in ./node_modules/ngx-toastr/fesm5/ngx-toastr.js Module not detected: Error: Unable to locate '/Users/vasanthan/Mean projects/node_modules/@angular/animations' in '/Users/vasanthan/Mean ...

Guide to integrating Mongoose typings with Angular 2 webpack starter

As a newcomer, I'm hoping this issue is straight forward. I am currently utilizing the angular2-webpack-starter found on GitHub. Based on the mongoose documentation, it appears that including their JavaScript file allows for accessing a global varia ...

The Angular ngFor directive seems to be failing to display the items within the array, even though accessing the items directly by using array[index

I've come across a strange issue with a simple program I'm working on. I want to display a list of numbers using an array, but when I try to use *ngFor in Angular, the elements don't render. However, if I manually reference each element in t ...

Controlling animation keyframes in Angular 2: a guide

Is there a way to manipulate CSS3/angular 2 animations using variables? Take a look at this modified code snippet from the official angular 2 animation docs: animations: [ trigger('flyInOut', [ state('in', style({position: &apos ...

Is there a specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Unlock the power of TypeScript by linking together function calls

I am looking for a way to create a type that allows me to chain functions together, but delay their execution until after the initial argument is provided. The desired functionality would be something like this: const getStringFromNumber = pipe() .then ...

Uncovering Module - which interface is missing a defined structure?

Can anyone explain why I am receiving this error in TypeScript 3.9.2: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type. The code triggering the error is shown below: const Module = function(){ ...

I am trying to replace the buttons with a dropdown menu for changing graphs, but unfortunately my function does not seem to work with the <select> element. It works perfectly fine with buttons though

I am currently working on my html and ts code, aiming to implement a dropdown feature for switching between different graphs via the chartType function. The issue I am facing is that an error keeps popping up stating that chartType is not recognized as a ...