0
votes

I have an API which for example returns the following model:

public class TestModel
{
    int Id { get; set; }

    public string UserName { get; set; }

    public string FirstName { get; set; }

    public string Surname { get; set; }

    public string DisplayName { get; set; }
}

I have an Angular Reactive form with the following FormGroup:

myForm = new FormGroup({
  id: new FormControl(),
  userName: new FormControl(),
  firstName: new FormControl(),
  surname: new FormControl()
});

When I load the data into my form I receive the following error: Cannot find form control with name: displayName.

I know the control isn't in my form group but I don't want it there as I would never change that value on the form. Is there a way round this or do I need to add it to the form group.

The form control isn't part of the HTML.It is not referenced anywhere on the Angular side and that is what I want.

<input type="text" [formControl]="myForm.get('userName')"/>
<input type="text" [formControl]="myForm.get('firstName')"/>
<input type="text" [formControl]="myForm.get('surname')"/>

Thanks

1
You don't need to add anything, but you need to show your template. - Roberto Zvjerković
If you don't want to access it in your code anyways, just don't give it a formControlName. - LeBavarois
The form control isn't part of the html and i don't want it to be - Sun

1 Answers

2
votes

This error occurs when the formControlName directive from the html template tries to look for the given name in the form. The solution would be to remove the formControlName="displayName" from the html.

Here is the function mentioned in the comment

   createFormGroup(data?:any):FormGroup{
     return new FormGroup({
       id: new FormControl(data ? data.id : null),
       userName: new FormControl(data ? data.userName : ''),
       firstName: new FormControl(data ? data.firstName : ''),
       surname: new FormControl(data ? data.surname : '')
     })
    }

Use it when you get the response

myForm = this.createFormGroup(response)