Is there a way for me to access the names of the controls in my form directly from the .html file?

I have a list where I am storing the names of my form controls. In order to validate these form controls, I need to combine their names with my code in the HTML file. How can I achieve this?

Below is my code:

.ts file

this.form = this.formBuilder.group({
   item0: ['', Validators.required],
   item1: ['', Validators.required]
});

formControls: string[] = [];
this.formControls.push('item0');
this.formControls.push('item1');

.html file

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div *ngFor="let item of formControls">
    <input formControlName="{{item}}"
     [ngClass]="{ 'is-invalid': f.item.errors }"/><!-- it must be: f.item0.errors, f.item1.errors-->
    <label>{{item}}</label>
    <div *ngIf="f.item.errors" class="invalid-feedback"> 
      <div *ngIf="f.item.errors.required">
        Item is required
      </div>
    </div>
  </div>
</form

Answer №1

If you want to join the form control names with the formGroup directive, you can utilize string interpolation.

<div *ngFor="let item of formControls"> 
  <input [formControlName]="item"
    [ngClass]="{ 'is-invalid': form.get(item)?.invalid }" />

   <div *ngIf="form.get(item)?.errors" class="invalid-feedback">
    <div *ngIf="form.get(item)?.errors.required"> 
      <label> {{item}} </label> is required 
    </div>
   </div>
</div>

Take a look at this code example: stackblitz

Answer №2

There is no need for an extra array to hold the form control name.

Loop through the controls in the FormGroup using *ngFor and KeyValuePipe.

<div *ngFor="let kvp of (form.controls | keyvalue)">
  <input
    [formControlName]="kvp.key"
    [ngClass]="{ 'is-invalid': kvp.value.errors }"
  />
  <label>{{kvp.key}}</label>
  <div *ngIf="kvp.value.errors" class="invalid-feedback">
    <div *ngIf="kvp.value.errors['required']">Item is required</div>
  </div>
</div>

Check out the demo on StackBlitz

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

Is it possible to link multiple references to a single Element/Node?

I am working on a function component that needs to pass the incoming ref from the parent to a div it is rendering. Additionally, I want to create and assign a separate ref inside the component to the same div. However, due to an element only accepting one ...

Exploring the functionalities of R.pick in TypeScript

Recently, I attempted the following code snippet: import R from 'ramda' import fs from 'fs' import path from 'path' import {promisify} from 'util' const readFile = promisify(fs.readFile) export async function disc ...

Opting In to Share Telemetry Data in Angular 8

Can someone help me understand how to enable the telemetry data sharing feature in Angular 8? I've done my research on the new features of Angular 8 and came across the option to opt-in for sharing usage data, but I'm unsure about where to find ...

I'm curious, what is the exact function of ...state?

Just dipping my toes into NgRx (redux) within Angular and I'm a bit puzzled by the use of ...state in the code snippet below. My understanding is that it functions as spread operator, but I can't grasp why the data attributes from the Interface S ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

Assigning variables in Angular ngFor loopFresh way to

Here is what I have: <div *ngFor="let item of order.items"> I want to show the result in this format: {{item.product.category.availability.selected.name.value}} {{item.product.category.availability.selected.id.value}} My goal is to assign all of ...

Issue with form using "target=_blank" to open PDF in web application home screen not functioning properly

I am encountering an issue in my Angular application where a form with target="_blank" successfully returns a PDF upon submission, but when accessed from the homescreen icon of the web-app in Android/Chrome, the new window opens blank without displaying th ...

angular-universal | firestore-admin | code: 'app/invalid-authentication' | connection timeout

import * as admin from 'firebase-admin'; var serviceAccount = require('./keys/keyfile.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://test.firebaseio.com" }); var registrationT ...

There seems to be an issue with the request header field Authorization, as it is not permitted by the Access-Control-Allow-Headers in

My project involves using Angular 2 for the client side and Laravel 5.4 for the server side. I have set up APIs in Laravel and am making requests to them from Angular 2. In Laravel, I have configured Oauth 2 passport service to authenticate all APIs. For ...

The parameter in Angular cannot be assigned a type of 'null'

@Injectable({ providedIn: 'root' }) export class AuthenticationService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.curren ...

Troubleshooting: ngModel in Angular 2 Component does not properly update the parent model

I have been attempting to develop a wrapper component for input elements like checkboxes, but I am facing an issue where the parent variable (inputValue) is not updating even though it has been defined as an ngModel. The code snippet for my component look ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

Guide on launching a bootstrap modal using ngIf

Hello everyone, I appreciate your patience as I am new to this! Currently, I am attempting to activate a Bootstrap modal using an ngIf condition. Specifically, the goal is for the modal to open when there is existing artwork present and allow for the addit ...

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

How can I move the cursor to the beginning of a long string in Mat-autocomplete when it appears at the end?

I'm struggling to figure out how to execute a code snippet for my Angular app on Stack Overflow. Specifically, I am using mat-autocomplete. When I select a name that is 128 characters long, the cursor appears at the end of the selected string instead ...

What methods can I utilize to manage the output generated by the C# backend project?

I'm new here and I'm thrilled to be asking my first question! :) Currently, I am working on a car rental project using C# for the backend and Angular for the frontend. I have encountered an issue while trying to register a new user with existing ...

An issue arose while compiling the template for 'AppRoutingModule', indicating that function expressions are not compatible with decorators

Currently, I have implemented the "CaseInsensitiveMatcher" based on the solution suggested by Alireza. However, I am facing an issue when attempting to create a production build as indicated by the following error message: "'urlMatch' referenc ...

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

Is having only one FCM token sufficient for storing data from multiple devices?

I'm currently working on an Angular website and looking to send push notifications to users subscribed on both desktop and mobile. I am utilizing Firebase Cloud Messaging for this purpose and wondering if storing a single FCM token will suffice for se ...

"Troubleshooting: Why are errors not appearing in ts-node

Whenever I encounter an error in my code while compiling with ts-node, the error does not seem to appear in the console. For instance:let data = await fs.readFileSync(path); In the following code snippet, I am using "fs" to read a file by passing a path ...