Sunday, December 1, 2019

Error: Cannot find control with name:

Hi Guys ,

In this blog I will share information related to error :

Error: Cannot find control with name:

The complete error log is as follows :


StatusComponent.html:2 ERROR Error: Cannot find control with name: 'sname'
    at _throwError (shared.ts:140)
    at setUpControl (shared.ts:36)
    at FormGroupDirective.addControl (form_group_directive.ts:132)
    at FormControlName._setUpControl (form_control_name.ts:278)
    at FormControlName.ngOnChanges (form_control_name.ts:207)
    at checkAndUpdateDirectiveInline (provider.ts:208)
    at checkAndUpdateNodeInline (view.ts:429)
    at checkAndUpdateNode (view.ts:389)
    at debugCheckAndUpdateNode (services.ts:431)
    at debugCheckDirectivesFn (services.ts:392)


You may get this error while using reactive Forms in Angular
Lets look at the code which caused this error .

import { Component, OnInit } from '@angular/core';
import { FormControl , FormGroup} from '@angular/forms';

@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.css']
})
export class StatusComponent implements OnInit {
  statusForm = new FormGroup(
    {
      fname : new FormControl('')
    }

  );
  
  constructor() { }

  ngOnInit() {
  }

  updateStatus() {
     
  }

}


<p>   {{statusForm.fname}} </p>
<form [formGroup]="statusForm">
<label>
  First Name 
  <input type="text"  formControlName="fname">
Second Name 
  <input type="text"  formControlName="sname">

</label>
 
</form>

You can see we have two form controls in the HTML but only one form control in Controller .



Lets fix this error . We need to add another FormControl to a FormGroup .

The working code is as below .

import { Component, OnInit } from '@angular/core';
import { FormControl , FormGroup} from '@angular/forms';

@Component({
  selector: 'app-status',
  templateUrl: './status.component.html',
  styleUrls: ['./status.component.css']
})
export class StatusComponent implements OnInit {
  statusForm = new FormGroup(
    {
      fname : new FormControl(''),
       sname : new FormControl('')
    }

  );
  
  constructor() { }

  ngOnInit() {
  }

  updateStatus() {
     
  }

}

Hope this helps . Thanks !

No comments:

Post a Comment

ec2-user@ec2 Permission denied