realist
realist

Reputation: 2375

Using FormcontrolName with label in angular 6

I have angular 6 project with reactive forms. I have a grid like below. Detail button, open a modal window and showing student infos. My html of dialog is like below. But it gave me No value accessor for form control with name: studentNumber error. Is my html logic is wrong?

This not working

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

When I tried like below, working perfectly. But, this is very long for writing everywhere.

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

When I tried like below, working perfectly

<input formControlName="studentNumber"> 

My grid

Upvotes: 5

Views: 23997

Answers (3)

Rafael Pizao
Rafael Pizao

Reputation: 841

A workaround... like a charm!! :)

input[readonly]{
   border: none;
   background: none;
   outline: none;
}

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

Upvotes: 0

yurzui
yurzui

Reputation: 214047

To not repeat yourself I would create simple directive for that case:

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

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

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

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

And use it as follows:

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

Ng-run Example

Upvotes: 12

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

IN component, you can create a getter method which will return form control value.

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

Upvotes: 3

Related Questions