0
votes

I have a simple angular template driven form with few inputs, span tags and button. I need to setValue to form from an object in my component.

I'm unable to setValue to span and button tags and I get the below error.

core.js:1365 ERROR Error: Uncaught (in promise): Error: No value accessor for form control with path: 'userSettings -> id'
Error: No value accessor for form control with path: 'userSettings -> id'
  at _throwError (forms.js:1901)
  at setUpControl (forms.js:1771)
  at resolvedPromise.then (forms.js:3851)
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
  at Object.onInvoke (core.js:3988)
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
  at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
  at zone.js:870
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
  at Object.onInvokeTask (core.js:3979)
  at _throwError (forms.js:1901)
  at setUpControl (forms.js:1771)
  at resolvedPromise.then (forms.js:3851)
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
  at Object.onInvoke (core.js:3988)
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
  at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
  at zone.js:870
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
  at Object.onInvokeTask (core.js:3979)
  at resolvePromise (zone.js:821)
  at zone.js:873
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
  at Object.onInvokeTask (core.js:3979)
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
  at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
  at drainMicroTaskQueue (zone.js:594)
  at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:499)
  at invokeTask (zone.js:1536)
  at HTMLAnchorElement.globalZoneAwareCallback (zone.js:1562)

My form html code

<form class="form-horizontal" role="form" (ngSubmit)="onSettingUpdateSubmit()" #settingsForm="ngForm" >
<fieldset ngModelGroup="userSettings">
  <legend><strong>Account Settings</strong></legend>
  <br>

  <div class="form-group row">
    <label class="col-md-3  col-form-label text-md-right">Id</label>
    <div class="col-md-4">
      <span class="fw-semi-bold" [ngModel]="id" id="id" name="id">{{ id }}</span>
    </div>
  </div>

  <div class="form-group row">
    <label for="firstName" class="col-md-3  col-form-label text-md-right">First Name</label>
    <div class="col-md-4">
      <input type="text"
             id="firstName"
             required
             [ngModel]="firstName"
             name="firstName"
             class="form-control"
             placeholder="Your first name">
    </div>
  </div>

  <div class="form-group row">
    <label class="col-md-3  col-form-label text-md-right">Active</label>
    <div class="col-md-4">
      <button type="button"
              id="active"
              [value]="active"
              [ngModel]="active"
              name="active"
              [ngClass]="active ? 'btn btn-success' : 'btn btn-danger'"
              (click)="onActiveMode()">{{ active ? 'Yes' : 'No'}}</button>
    </div>
  </div>
</fieldset>

<div class="form-actions">
  <div class="btn-block text-center">
    <button type="submit"
            class="btn btn-primary"

            [disabled]=!settingsForm.valid>Update</button>
  </div>
</div>

The settingsService in my component will return an object from my API as below object.

{
    "id":"12345",
    "firstName":"Victor",
    "active":true
}

My settings.compontent.ts

export class SettingsComponent implements OnInit {

 ngOnInit() {
      this.settingsService.getUserSettings('12345')
         .subscribe(
               (response: UserSettings) => {

                    console.log(response);

                    // this.settingForm.setValue({
                    //   userSettings: response
                    // });

                    this.settingForm.form.patchValue({
                       userSettings: response
                    });
                },
                (error) => console.log(error)
             );
           }

 onSettingUpdateSubmit() {
     console.log(this.settingForm.value.userSettings);
 }
}

When I click the button Update in my form it returns all the complete object with values (preset in my component for testing purpose).

1
The setValue and patchValue are for reactive forms. You are using template-driven forms. With template-driven forms the values are set into the controls using two-way binding. - DeborahK
I was able to resolve the error by adding ngDefaultControl="id" for span tag. I'm using @ViewChild to access my complete form with ngModelGroup='userSettings' so, I use setValue or patchValue to set as whole. - vyeluri5
OK. But FYI ... the Angular team highly recommends not mixing template-driven form syntax and reactive form syntax. - DeborahK

1 Answers

0
votes

It looks like you are mixing some template-driven form syntax with reactive form syntax and it won't work.

Here is an example of one of my template-driven form controls:

  <div class="form-group row">
    <label class="col-md-2 col-form-label"
           for="firstNameId">First Name</label>
    <div class="col-md-8">
      <input class="form-control"
             id="firstNameId"
             type="text"
             placeholder="First Name (required)"
             required
             minlength="3"
             [(ngModel)]=customer.firstName
             name="firstName"
             #firstNameVar="ngModel"
             [ngClass]="{'is-invalid': (firstNameVar.touched || firstNameVar.dirty) && !firstNameVar.valid }" />
      <span class="invalid-feedback">
        <span *ngIf="firstNameVar.errors?.required">
          Please enter your first name.
        </span>
        <span *ngIf="firstNameVar.errors?.minlength">
          The first name must be longer than 3 characters.
        </span>
      </span>
    </div>
  </div>

Notice that it uses two-way binding: [(ngModel)]=customer.firstName

And it's binding to the firstName property of the customer object. In your case, you need to define a user object instead. Something like this:

export class SettingsComponent implements OnInit {
     user: UserSettings;

     ngOnInit() {
          this.settingsService.getUserSettings('12345')
             .subscribe(
                   (response: UserSettings) => {
                        console.log(response);
                        this.user = response;
                    },
                    (error) => console.log(error)
                 );
               }

     onSettingUpdateSubmit() {
         console.log(this.settingForm.value.userSettings);
     }
    }

And your HTML:

[(ngModel)]="user.firstName"

This will automatically populate your form with the values retrieved from your setting service.

I have a complete example here: https://github.com/DeborahK/Angular2-ReactiveForms/tree/master/Demo-Start-Updated