Angular - Automatically blur input field in a Reactive Form

I'm encountering a strange problem. Check out the demo

.ts

import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.formBuilder.group({
      'options': this.formBuilder.array([this.createOption()])
    });

  }

  createOption(): FormGroup {
    return this.formBuilder.group({
      'name': [null]
    });
  }
}

.html

<form novalidate [formGroup]="myForm" >
    <div formArrayName="options" class="mt-3">
          <div [formGroupName]="i" *ngFor="let option of myForm.get('options').value; let i = index;">
<input id="{{'name' + i}}" autocomplete="off" type="text" class="form-control" aria-label="Name"
                    formControlName="name">
          </div>
    </div>
</form>

I have a form with multiple options' name field. In the HTML, I loop through each option to display the fields. However, if I enter any character in the input field, it automatically loses focus.

If I change

*ngFor="let option of myForm.get('options').value; let i = index;"
to
*ngFor="let option of myForm.get('options').controls; let i = index;"
, the issue is resolved.

But when I try to deploy it to production and run

ng build --prod

An error is thrown:

Property 'controls' does not exist on type 'AbstractControl'.

I need assistance with this problem.

Answer №1

If you want to iterate through the controls in the 'options' form group of myForm, use myForm.get('options').controls instead of myForm.get('options').value.

Here's the corrected code snippet:

<form novalidate [formGroup]="myForm" >
    <div formArrayName="options" class="mt-3">
        <div [formGroupName]="i" *ngFor="let option of myForm.get('options').controls; let i = index;">
             <input id="{{'name' + i}}" autocomplete="off" type="text" class="form-control" aria-label="Name" formControlName="name">
        </div>
   </div>
</form>

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

Using currency symbols in Angular 2

I'm currently in Australia and trying to display some currency values. I have the following code: {{ portfolio.currentValue | currency : 'AUD' : true : '4.0' }} However, the result I am getting is A$1,300,000. Is there a way to c ...

Unable to retrieve content in NGX-Quill upon submission

I am currently using "ngx-quill": "^14.3.0" along with "@angular/core": "~12.2.0". It is registered in the app module: QuillModule (not for root). And also in the lazy loaded module: QuillModule (not for root). public editor = { toolbar: [ ...

Issue encountered with the inability to successfully subscribe to the LoggedIn Observable

After successfully logging in using a service in Angular, I am encountering an error while trying to hide the signin and signup links. The error message can be seen in this screenshot: https://i.stack.imgur.com/WcRYm.png Below is my service code snippet: ...

What is the reason buttons in mat-menus do not submit?

I have implemented a mat-menu to showcase a list of choices for the user. The objective is to trigger the submission of my formGroup when a user selects an option from the menu. dropdown.component.html <form [formGroup]="myForm" (ngSubmit)=onSubmit(my ...

Mastering ngClass for validation in Angular 2: Step-by-step guide

I am facing an issue with a form I have created where I applied ngclass to display an error when the form value is missing. However, the error is showing up when the form is initially loaded. It seems that by default, my input tag is invalid when the form ...

Switching the Angular host using @input directive

I am exploring how to modify the appearance of my component using the angular @Input() decorator. The reason for this is because I encountered difficulties in: Modifying the CSS via @ViewChild as it was not initialized at ngOnInit() Applying styles throu ...

What could be the reason for certain Angular modules importing successfully while others fail to do so?

I am encountering an issue with a module that I am struggling to import. Using Typescript 2.7 and Node 10 The pxl-ng-security module is showing an error in both VSCode and VS2019. When hovering over it, error 2307 is displayed. Below is the import secti ...

Angular's reactive form feature does not have built-in support for ngIf

I am facing an issue with a form group where I need to display one of the required inputs using ngIf. However, even if this input does not exist, the form control still checks it and returns that the form is not valid. Here is my code: HTML: <form [form ...

Ensuring Commitments in the ForEach Cycle (Typescript 2)

Having trouble with promise chains after uploading images to the server in Angular 2 and Typescript. Let's come up with some pseudo-code: uploadImages(images):Promise<any> { return new Promise((resolve, reject) => { for (let imag ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Initialization Error: Blank Page Detected in APP_INITIALIZER

I've encountered an issue while using APP_INITIALIZER. The function appears to be functioning correctly, as it hits the endpoint and returns with resolve(true). However, all I see on the screen is a blank page. There are no errors in the console. Here ...

Repetitive execution of Angular service function upon route change

In my Angular 8 project, there is a service function responsible for copying data. However, I encountered an issue where if I copy the data on a page, navigate to another page, and then return to the original page to copy the data again, it ends up duplica ...

Implementing Angular *ngFor to Reference an Object Using Its Key

myjson is a collection of various hijabs and headscarves: [ { "support": 2, "items": [ [ { "title": "Segitiga Wolfis", "price": 23000, "descripti ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

What sets apart using (@Inject(Http) http: Http) from not using it?

Following a recent query, I now have a new question. What sets apart these two approaches? Here is the original code I used: import {Http, HTTP_PROVIDERS} from 'angular2/http'; @Component({ viewProviders: [HTTP_PROVIDERS], ..// constructor(h ...

Frontend Development with Angular 7+: A Modular Approach

I'm aiming to develop a frontend application that is modularized, allowing for the release of each module independently. However, I've run into an issue where creating angular modules for each frontend module requires building all modules togeth ...

In Angular, I aim to invoke the this.addDispatchToReceive method whenever the outcome is successful within each forEach iteration

How can I ensure that the values from this.stockItemDispatch are obtained in this.addDispatchToReceive(); during each iteration of a loop, instead of only getting the last stock value? The issue is that the subscribe function runs after the foreach cycle ...

Tips for incorporating the Sanitize library into Angular 6:

What is the most effective library for sanitization in Angular 6 to enhance security measures? Since injecting dependencies can be tricky, what are some recommended methods for implementing this in an Angular 6 project? ...

Harmonize the connectivity between an Angular - .NET application and the Google Calendar API

I am currently working on integrating the Google Calendar API into my angular .NET application using OAuth2. The goal is to allow each user to see their own calendar as soon as they log in. One idea I have is to save the generated code into our database f ...