Cannot find control with name: 'student.id'

Asked

Viewed 608 times

-1

I’m trying to send the student id, but this giving error.

Tag-presenca.component.html:

<form [formGroup]="formulario">
  <div class="mdl-grid mdl-cell--4-col">
      <div class="mdl-cell mdl-cell--10-col">
        <mat-form-field appearance="outline">
          <mat-label>Código do Aluno</mat-label>
          <input matInput type="number" formControlName="aluno.id" (keyup)="onSubmit()">
          <mat-error *ngIf="formulario.get('aluno.id').hasError('required')">
            Campo obrigatório
          </mat-error>
        </mat-form-field>
      </div>

    </div>
  </form>

Marque-presenca.component.ts

  ngOnInit() {
    this.formulario = this.formBuilder.group({
      aluno: this.formBuilder.group({
        id: [null]
      }),
    });
  }
  onSubmit() {
    console.log('chamou');
    if (this.formulario.valid) {
      console.log('1 - ', this.formulario.value);
      this.presencaService.post(this.formulario.value).subscribe(() => {
        this.abrirSnackBar('Presença registrada com sucesso!');
          // window.location.href = '/novo';
        this.formulario.reset();
      }, err => {
        this.abrirSnackBar(err.error.message);
      });
    }
  }

Marcarpresencacomponent.html:4 ERROR Error: Cannot find control with name: 'student.id' at _throwError (Forms.js:3357) at setUpControl (Forms.js:3181) At Formgroupdirective.addControl (Forms.js:7345) At Formcontrolname. _setUpControl (Forms.js:8070) At Formcontrolname.ngOnChanges (Forms.js:7993) checkAndUpdateDirectiveInline (core.js:31906) checkat AndUpdateNodeInline (core.js:44367) checkat AndUpdateNode (core.js:44306) at debugCheckAndUpdateNode (core.js:45328) at debugCheckDirectivesFn (core.js:45271)

1 answer

1

To access a control within a group of controls you need to first set the group and then call the control

You can use the directive formGroupName that works like the formControlName, but the control must be a group:

<form [formGroup]="formulario">
    <div formGroupName="aluno">
        <input formControlName="id"/>
    </div>
</form>

You can also use the directive formGroup as used in the element form:

<form [formGroup]="formulario">
    <div [formGroup]="formulario.controls.aluno">
        <input formControlName="id"/>
    </div>
</form>

I don’t know that Angular understands the point (.) as a group sub-control. Angular even understands in the Javascript API: formulario.get('controle.subcontrole') but not in HTML

  • Thank you very much man, it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.