Harnessing the Power of FormControlName and Labels in Angular 6

In my project using Angular 6 and reactive forms, I have a grid with a Detail button that opens a modal window displaying student information. However, when implementing the HTML for the dialog box as shown below, I encountered an error message stating:

No value accessor for form control with name: studentNumber
. Is there an issue with my HTML logic?

The current implementation does not seem to be functioning correctly.

<form [formGroup]="studentForm">
  <p-dialog header="Student Detail" [(visible)]="displayStudentForm">
    <div class="p-grid">
        <label>Student Number</label>
        <label formControlName="studentNumber"></label>
    </div>
    <div class="p-grid">
        <label>Student Age</label>
        <label formControlName="studentAge"></label>
    </div>
    <div class="p-grid">
        <label>Student Type</label>
        <label formControlName="studentType"></label>
    </div>
  </p-dialog>
</form>

Although the following code works perfectly, it is quite lengthy to write repeatedly throughout the application.

<label>{{studentForm.controls.studentNumber.value}}</label>

This simpler implementation also works perfectly:

<input formControlName="studentNumber"> 

https://i.sstatic.net/r8dbp.png

Answer №1

In order to avoid redundancy, I recommend creating a simple directive specifically for this scenario:

import { Directive, HostBinding, Optional, Input } from '@angular/core';
import { ControlContainer} from '@angular/forms';

@Directive({
  selector: 'label[controlName]',
})
export class CustomLabelDirective {
  @Input() controlName: string;

  constructor(@Optional() private parent: ControlContainer) {}

  @HostBinding('textContent')
  get labelValue() {
    return this.parent ? this.parent.control.get(this.controlName).value : '';
  }
}

You can then implement it like this:

<label controlName="studentNumber"></label>

Click here for a Ng-run Example

Answer №2

Within a component, you have the ability to create a getter method that will retrieve the value of a form control.

<form [formGroup]="studentForm">
  <p-dialog header="Student Detail" [(visible)]="displayStudentForm">
    <div class="p-grid">
        <label>Student Number</label>
        <label>{{getControlLabel('studentNumber')}}</label>
    </div>
    <div class="p-grid">
        <label>Student Age</label>
        <label>{{getControlLabel('studentAge')}}</label>
    </div>
    <div class="p-grid">
        <label>Student Type</label>
        <label>{{getControlLabel('studentType')}}</label>
    </div>
  </p-dialog>
</form>

Component:

getControlLabel(type: string){
 return studentForm.controls[type].value;
}

Answer №3

This clever solution worked perfectly! :)

input[disabled]{
   border: none;
   background-color: transparent;
   outline: none;
}

...
<input disabled formControlName="studentNumber">
...

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 a for-loop in Typescript to iterate over objects in an array

Consider an Array structured as follows: let bodyDataAnswer = { 'answers':[{ 'question_id':this.verifyCustomer.questions[0].id, 'int_result':this.verifyCustomer.questions[0].answer_template.answers["0"].int_result, ...

What is the best way to target all select2 elements with a single button click?

Utilizing the Select2 feature of angular for multiple selection, I am in need of a function that allows me to select all elements with a single click on a button or checkbox. https://www.npmjs.com/package/ng-select2 My attempt at inserting all ele ...

Is TypeScript capable of comprehending Svelte components?

When it comes to Svelte, the final output is native JavaScript classes, which TypeScript can understand. However, before TypeScript can recognize Svelte components, they must first be compiled from their initial .html form. This can lead to a 'cannot ...

Encountered an issue while trying to assign a value to the 'value' property on an 'HTMLInputElement' within a reactive form

When I upload a picture as a data record, the image is sent to a server folder and its name is stored in the database. For this editing form, I retrieve the file name from the server and need to populate <input type="file"> in Angular 6 using reacti ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

Developing a project using npm and Node.js with Typescript has been smooth sailing so far. However, an issue has arisen

Recently, I came across a helpful guide on setting up a Node.js project in Typescript on this website: https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html The guide also provides instructions for auto-recompilation upon changes when using npm st ...

Angular lazy loading routes do not function as intended

I currently have a project that is divided into different modules. Among these modules, the ones that are lazy loaded include the about and contact modules. The navigation menu containing the router links is located in a feature module alongside the header ...

Setting up project with local library installation in Angular 7 - Project configuration

I am currently working on an Angular application that consists of a core module and a shared module. The structure of my project is as follows: ./repo | projects | core | shared | src (my app) When I build libraries, the output folder is dist ...

Retrieving the value that is not currently selected in a mat-select component

In my mat-table, there is a mat-select component displayed like this: <mat-select multiple placeholder="{{element.name}}" [(value)]="selectedCol" (selectionChange)="selectionChange($event)" [disabled]="!selection.isSelected(element.id)"> & ...

Error encountered while loading a plugin in Typescript and RequireJS compilation process

Currently, I am working on a Typescript application in Visual Studio 2015 where RequireJS is used for loading modules. I have successfully loaded various modules from .ts classes and external libraries by using their typing .d.ts files. However, I have en ...

typescript ways to exclude enum values

I am working with enums in TypeScript. enum Status { Cancelled = 'cancelled', Completed = 'completed', Created = 'created' } Now, I need to create another enum that includes only the values Completed and Created. enum S ...

Tips for capturing the output of a dynamically rendered component in Angular 8

I need to capture the output from a rendered component using ViewChild. The content of ViewChild is displayed after an ngIf condition is met. Here is the template code: <div *ngIf="isModalVisible" class="modal" tabindex="-1" role="dialog"> <di ...

Generating a JavaScript bundle using the npm TypeScript compiler

Is there a way to compile TypeScript source files into one JavaScript bundle file? We have developed a tool on node.js and are currently using the following TypeScript compilation code: var ts = require('typescript'); ... var program = ts.creat ...

The hook from Supabase is facing issues with proper importing

This project is a Spotify clone. The issue I'm facing is related to importing the hook. The error message reads: React Hook "useSupabaseClient" is called in function "useloadArtistImage" that is neither a React function component nor a custom React H ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

Unable to instantiate a Vue reference with a potential null type

When working in Vue v3, I encountered a situation where I needed to create a ref with a type that could possibly be null. This specific scenario in my app involves data that starts off as null and then gets populated after loading completes. Just to illus ...

Cannot send response headers once they have already been sent to the client [NEXTJS]

Currently, I am engrossed in a personal project focused on creating a dashboard using NextJS. This project serves as an opportunity for me to delve into learning NextJS and the fundamental concepts of TypeScript. My primary challenge at the moment revolves ...

"Converting an angular date-picker into a popup-date-picker: A step-by-step

I am currently working on a project in Plunker and I would like to implement an Angular date-picker-popup similar to the one in my design. Any suggestions or ideas on how to achieve this? Thank you in advance! ...

"An issue occurred while trying to utilize the output received from the angular service (undefined

I currently have two variables declared in my Typescript class: private myServiceSubscription: Subscription; myVar: myDto[] = []; Within the constructor: this.myServiceSubscription = this.deliveryPointService .getPostalAddresses() .subsc ...

Do you think it's important to include a maxlength validation message for an input field in Angular?

Utilizing the maxlength attribute on a form field not only enables Angular's default validation, it also restricts input beyond the specified length from being typed into the text box. So, does this imply that displaying an error message for violating ...