Search code examples
angularenumsangular-material-7

Convert enum to material select in my component


Now I have a some problem with enum. I want make mat-select in component with enum values, but I'm not understand, how is possible. I tried it, but but nothing worked

My ts component code

    import { Component, OnInit } from '@angular/core';
    import { FormControl, FormGroup } from '@angular/forms';
    import { select, Store } from '@ngrx/store';
    
    import { Currency } from 'src/app/enums/CurrencyType';
    import { Edition } from 'src/app/enums/EditionType';
    import { Author } from 'src/app/models/Author';
    
    import { getAuthorsList } from 'src/app/store/author/author.actions';
    import { getAuthorsSelector } from 'src/app/store/author/author.selector';
    
    @Component({
      selector: 'app-printing-edition-item',
      templateUrl: './printing-edition-item.component.html',
      styleUrls: ['./printing-edition-item.component.css']
    })
    export class PrintingEditionItemComponent implements OnInit {
    
      type: Edition -- my enum
    
      constructor(private store: Store) {
       }
    }

my enum

export enum Edition{
  None = 0,
  Journal = 1,
  Newspaper = 2,
  Book = 3
}

my try in HTML:

     <mat-form-field>
              <mat-label>Category</mat-label>
              <mat-select formControlName="type">
                <mat-option *ngFor="let item of type" value="item">type[item]</mat-option>
              </mat-select>
    </mat-form-field>

Solution

  • You could use something like that:

    export class PrintingEditionItemComponent implements OnInit {
    
        type = Edition;
        keys: string[];
        
        constructor(private store: Store) { }
    
        ngOnInit() {
            this.keys = Objects.keys(this.type).filter(Number);
            this.selectedEdition = Edition.Foo;
        }
    }
    

    And in your template:

    <mat-form-field>
        <mat-label>Category</mat-label>
        <mat-select formControlName="selectedEdition">
            <mat-option *ngFor="let item of keys" value="item">type[item]</mat-option>
        </mat-select>
    </mat-form-field>