Select using Enum

Asked

Viewed 437 times

1

I have a form where one of the fields is a select, and this select is an Enum, I can popular it but can not send the value, always goes with value 0 when I do the post. I wanted a select with two options

HTML:

<form class="mat-dialog-content" (ngSubmit)="(submit)" #formControl="ngForm">

  <div class="form">
    <mat-form-field color="accent">
      <textarea matInput #input class="form-control" placeholder="Nome" [(ngModel)]="data.name" name="name" required></textarea>
      <mat-error *ngIf="formControl.invalid">{{ getErrorMessage() }}
      </mat-error>
    </mat-form-field>
  </div>
  <div class="form">
    <mat-form-field>
      <mat-select matNativeControl required>
        <mat-option *ngFor="let item of (editoriaTipo | keys)" [value]="item.key" [(ngModel)]="data.type">{{ item.value }}</mat-option>
      </mat-select>
    </mat-form-field>
  </div>
  <div mat-dialog-actions>
    <button mat-button [type]="submit" [disabled]="!formControl.valid" [mat-dialog-close]="1" (click)="confirmAdd()">
        Savar
      </button>
    <button mat-button (click)="onNoClick()" tabindex="-1">Cancelar</button>
  </div>
</form>

Service:

  addEditorias(editorias: Editorias): void {
    this.httpClient.post(this.API_URL_Ed, editorias).subscribe(
      data => {
        this.dialogData = editorias;
        // this.editoriaService.showToaster("Successfully added", 3000);
      },
      (err: HttpErrorResponse) => {
        // this.editoriaService.showToaster(
        //   "Error occurred. Details: " + err.name + " " + err.message,
        //   8000
        // );
      }
    );
  }

Enum:

export enum EditoriaType {
  programa = 1,
  editoria = 2,
}

Object:

import { EditoriaType } from "../enum/editoria-type";

export interface Editorias {
  id: number;
  name: string;
  type: EditoriaType;
  dataDeCriacao: Date;
  dataDeAtualizacao: Date;
  deletado: boolean;
}

He also makes the mistake: Editoriacriarcomponent.html:68 ERROR Error: If ngModel is used Within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

Always register like this with type 0, even if I choose:

{
name: "1",
type: 0,
id: "950a1854-a66d-43cd-0bef-08d671c5dec9",
}

1 answer

1


Hello,

you can try to use this way:

  ...

  listaEditoria = EditoriaType;
  keys:any;

  constructor(){
    this.keys = Object.keys( this.listaEditoria ).filter(Number)
    console.log( 'KEys', this.keys )
  }

and in select:

<mat-option *ngFor="let key of keys" [value]="key" >
   {{listaEditoria[ key ]}}
</mat-option>

I hope this helps...

Browser other questions tagged

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