【问题标题】:Convert enum to material select in my component在我的组件中将枚举转换为材料选择
【发布时间】:2020-11-09 17:14:45
【问题描述】:

现在我遇到了枚举问题。 我想在具有枚举值的组件中进行 mat-select,但我不明白,这怎么可能。 我试过了,但没有任何效果

我的ts组件代码

    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) {
       }
    }

我的枚举

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

我在 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>

【问题讨论】:

    标签: angular enums angular-material-7


    【解决方案1】:

    你可以使用类似的东西:

    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;
        }
    }
    

    在你的模板中:

    <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>
    

    【讨论】:

    • keys 必须是 string[] 才能使用Objects.keys(this.type).filter(Number)
    • 刚刚修好了:)
    • 枚举中可能有问题?你怎么看?
    • 在控制台中我看到了这个`ERROR TypeError: Cannot convert undefined or null to object`
    • 这是一个项目示例,也许这会对您有所帮助stackblitz.com/edit/select-enum-angular?file=src/app/…
    猜你喜欢
    • 1970-01-01
    • 2013-01-17
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2020-08-21
    • 2021-01-04
    相关资源
    最近更新 更多