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">
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With