Home > Net >  Angular2 select form not capturing value
Angular2 select form not capturing value

Time:11-21

I'm using Angular 14 trying to create a select form reading the options from an array in my component. The select options are correctly populated, but when I send the form, the selected option value is not being sent. It just keep it empty. Any suggestions about what could be causing this?

<mat-label>Perfil</mat-label>
    <mat-select name="perfil">
       <mat-option *ngFor="let perfil of perfis" 
       [value]="perfil.value">{{ perfil.title }}
       </mat-option>
    </mat-select>

In the component the array is:

  perfis: {title: string, value: number }[] = [
      { "title": "Admin", "value": 1 },
      { "title": "Coordenador", "value": 2 },
      { "title": "Colaborador", "value": 3 },
    ];

Inside form component's constructor:

this.form = this.formBuilder.group({
    id: [''],
    login: [''],
    password: [''],
    nome: [''],
    rg: [''],
    cpf: [''],
    telefone: [''],
    email: [''],
    ativo: [''],
    perfil: ['']
  });

To submit the form:

onSubmit() {
console.log(this.form.value); // this is where I see the field is always empty
this.usersService.save(this.form.value)
.subscribe(
  data => this.onSuccessInsertion('Informação inserida do banco de dados.'),
  error => this.onError('Não foi possível salvar esta informação no banco de dados.')
  );

}

Maybe I'm listing the options but I'm not capturing the value after being selected? If so, how should I do this? I've read that you could use [selected], but that was not even recognized by Angular.

I noticed that maybe it is because the value is being captured as a string. I read in another post that [value]="..." only supports string values and [ngValue]="..." supports any type So it would be needed to use [ngValue]="perfil.value" in the HTML, but it gives me error if I [ngValue] instead of [value]. The error message is:

Can't bind to 'ngValue' since it isn't a known property of 'mat-option'.

  1. If 'mat-option' is an Angular component and it has 'ngValue' input, then verify that it is part of this module.
  2. If 'mat-option' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
  3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.ngtsc(-998002)

CodePudding user response:

It seems the select is not associated with a control in the FormGroup. Because of this, Angular doesn't know that the select should change the perfil control in the form. Assuming you set the FormGroup earlier in the template, you can bind the select to that control with the formControlName directive, like this:

<mat-select name="perfil" [formControlName]="'perfil'">
    <mat-option *ngFor="let perfil of perfis"
    [value]="perfil.value">{{ perfil.title }}
    </mat-option>
</mat-select>
  • Related