programing

Angular2의 열거 형을 기반으로 선택

nasanasas 2020. 11. 20. 09:02
반응형

Angular2의 열거 형을 기반으로 선택


이 열거 형이 있습니다 ( TypeScript를 사용 하고 있습니다 ).

export enum CountryCodeEnum {
    France = 1,
    Belgium = 2
}

다음과 같이 옵션에 대해 열거 형 정수 값을 값으로, 열거 형 텍스트를 레이블 로 사용하여 양식 에서 선택작성하고 싶습니다.

<select>
     <option value="1">France</option>
     <option value="2">Belgium</option>
</select>

어떻게 할 수 있습니까?


어레이를 생성하여 간소화 된 update2

@Pipe({name: 'enumToArray'})
export class EnumToArrayPipe implements PipeTransform {
  transform(value) : Object {
    return Object.keys(value).filter(e => !isNaN(+e)).map(o => { return {index: +o, name: value[o]}});
  }
}

@Component({
  ...
  imports: [EnumsToArrayPipe],
  template: `<div *ngFor="let item of roles | enumsToArray">{{item.index}}: {{item.name}}</div>`
})
class MyComponent {
  roles = Role;
}

최신 정보

대신에 pipes: [KeysPipe]

사용하다

@NgModule({
  declarations: [KeysPipe],
  exports: [KeysPipe],
}
export class SharedModule{}
@NgModule({
  ...
  imports: [SharedModule],
})

실물

https://stackoverflow.com/a/35536052/217408 에서 keys파이프 사용

enum과 함께 제대로 작동하도록 파이프를 약간 수정해야했습니다 (또한 enum 항목의 이름을 얻는 방법 참조 ).

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (var enumMember in value) {
      if (!isNaN(parseInt(enumMember, 10))) {
        keys.push({key: enumMember, value: value[enumMember]});
        // Uncomment if you want log
        // console.log("enum member: ", value[enumMember]);
      } 
    }
    return keys;
  }
}

@Component({ ...
  pipes: [KeysPipe],
  template: `
  <select>
     <option *ngFor="let item of countries | keys" [value]="item.key">{{item.value}}</option>
  </select>
`
})
class MyComponent {
  countries = CountryCodeEnum;
}

플 런커

* ngFor를 사용하여 객체 키를 반복하는 방법 도 참조하십시오 .


새 파이프를 만들고 싶지 않은 경우 한 가지 더 해결책. 도우미 속성으로 키를 추출하여 사용할 수도 있습니다.

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <select>
        <option *ngFor="let key of keys" [value]="key" [label]="countries[key]"></option>
      </select>
    </div>
  `,
  directives: []
})
export class App {

  countries = CountryCodeEnum

  constructor() {
    this.keys = Object.keys(this.countries).filter(k => !isNaN(Number(k)));
  }
}

데모 : http://plnkr.co/edit/CMFt6Zl7lLYgnHoKKa4E?p=preview

편집하다:

문자열 대신 숫자로 옵션이 필요한 경우 :

  • 교체 [value][ngValue]
  • .map(Number)뒤에 추가.filter(...)

Angular2 v2.0.0에 대한 매우 간단한 방법이 있습니다. 완전성을 위해 반응 형을country 통해 select 의 기본값을 설정하는 예를 포함했습니다 .

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <select id="country" formControlName="country">
        <option *ngFor="let key of keys" [value]="key">{{countries[key]}}</option>
      </select>
    </div>
  `,
  directives: []
})
export class App {
  keys: any[];
  countries = CountryCodeEnum;

  constructor(private fb: FormBuilder) {
    this.keys = Object.keys(this.countries).filter(Number);
    this.country = CountryCodeEnum.Belgium; //Default the value
  }
}

Angular 앱에서 공유되는 간단한 유틸리티 함수를 사용하여을 enum표준 배열로 변환하여 선택 항목을 빌드 하는 것을 선호했습니다 .

export function enumSelector(definition) {
  return Object.keys(definition)
    .map(key => ({ value: definition[key], title: key }));
}

구성 요소의 변수를 다음으로 채 웁니다.

public countries = enumSelector(CountryCodeEnum);

그런 다음 Material Select를 이전 배열 기반으로 채 웁니다.

<md-select placeholder="Country" [(ngModel)]="country" name="country">
  <md-option *ngFor="let c of countries" [value]="c.value">
    {{ c.title }}
  </md-option>
</md-select>

이 스레드에 감사드립니다!


"0" (예 : "Unset")을 생략하지 않는 또 다른 유사한 솔루션 입니다. filter (Number) IMHO를 사용하는 것은 좋은 접근 방식이 아닙니다.

@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <select>
    <option *ngFor="let key of keys" [value]="key" [label]="countries[key]"></option>
  </select>`,
  directives: []
})

export class App {
  countries = CountryCodeEnum;

  constructor() {
    this.keys = Object.keys(this.countries).filter(f => !isNaN(Number(f)));
  }
}

// ** NOTE: This enum contains 0 index **
export enum CountryCodeEnum {
   Unset = 0,
   US = 1,
   EU = 2
}

Angular 6.1 이상 KeyValuePipe부터는 아래와 같이 내장을 사용할 수 있습니다 (angular.io 문서에서 붙여 넣기).

물론 열거 형에 인간 친화적 인 읽을 수있는 문자열이 포함되어 있다고 가정합니다. :)

@Component({
  selector: 'keyvalue-pipe',
  template: `<span>
    <p>Object</p>
    <div *ngFor="let item of object | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
    <p>Map</p>
    <div *ngFor="let item of map | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
  </span>`
})
export class KeyValuePipeComponent {
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  map = new Map([[2, 'foo'], [1, 'bar']]);
}


이 답변의 또 다른 스핀 오프이지만 실제로 값을 버그 인 문자열로 변환하는 대신 숫자로 매핑합니다. 0 기반 열거 형에서도 작동합니다.

@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <select>
<option *ngFor="let key of keys" [value]="key" [label]="countries[key]"></option>
  </select>`,
  directives: []
})

export class App {
  countries = CountryCodeEnum;

  constructor() {
    this.keys = Object.keys(this.countries)
                      .filter(f => !isNaN(Number(f)))
                      .map(k => parseInt(k));;
  }
}

문자열 열거 형으로 이것을 시도 할 수 있습니다.

내 문자열 열거 형에는 다음과 같은 정의가 있습니다.

    enum StatusEnum {
        Published = <any> 'published',
        Draft = <any> 'draft'
    }

다음과 같은 방식으로 js로 변환됩니다.

   {
       Published: "published", 
       published: "Published", 
       Draft: "draft", 
       draft: "Draft"
   }

내 프로젝트에 몇 가지가 있으므로 공유 서비스 라이브러리에 작은 도우미 함수를 만들었습니다.

   @Injectable()
   export class UtilsService {
       stringEnumToKeyValue(stringEnum) {
           const keyValue = [];
           const keys = Object.keys(stringEnum).filter((value, index) => {
               return !(index % 2);
           });

           for (const k of keys) {
               keyValue.push({key: k, value: stringEnum[k]});
           }

           return keyValue;
       }
   }

구성 요소 생성자에서 초기화하고 다음과 같이 템플릿에 바인딩합니다.

구성 요소에서 :

    statusSelect;

    constructor(private utils: UtilsService) {
        this.statusSelect = this.utils.stringEnumToKeyValue(StatusEnum);
    }

템플릿에서 :

    <option *ngFor="let status of statusSelect" [value]="status.value">
        {{status.key}}
    </option>

Don't forget to add the UtilsService to the provider array in your app.module.ts so you can easily inject it in different components.

I'm a typescript newbie so please correct me if I'm wrong or if there are better solutions.


This is the best option which you can apply without any pipes or extra code.

import { Component } from '@angular/core';

 enum AgentStatus {
    available =1 ,
    busy = 2,
    away = 3,
    offline = 0
}


@Component({
  selector: 'my-app',
  template: `
  <h1>Choose Value</h1>

  <select (change)="parseValue($event.target.value)">
    <option>--select--</option>
    <option *ngFor="let name of options"
        [value]="name">{{name}}</option>
  </select>

  <h1 [hidden]="myValue == null">
    You entered {{AgentStatus[myValue]}}

  </h1>`
})
export class AppComponent { 


  options : string[];
  myValue: AgentStatus;
  AgentStatus : typeof AgentStatus = AgentStatus;

  ngOnInit() {
    var x = AgentStatus;
    var options = Object.keys(AgentStatus);
    this.options = options.slice(options.length / 2);
  }

  parseValue(value : string) {
    this.myValue = AgentStatus[value];

  }
}

참고URL : https://stackoverflow.com/questions/35750059/select-based-on-enum-in-angular2

반응형