Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 542
realist Avatar asked Nov 11 '18 12:11

realist


1 Answers

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

like image 181
yurzui Avatar answered Sep 26 '22 22:09

yurzui