Angular2 뷰 템플릿의 패스넘
angular2 뷰 템플릿에서 열거형을 사용할 수 있습니까?
<div class="Dropdown" dropdownType="instrument"></div>
문자열을 입력으로 전달합니다.
enum DropdownType {
instrument,
account,
currency
}
@Component({
selector: '[.Dropdown]',
})
export class Dropdown {
@Input() public set dropdownType(value: any) {
console.log(value);
};
}
그러나 열거형 구성을 전달하는 방법은 무엇입니까?템플릿에 다음과 같은 것이 필요합니다.
<div class="Dropdown" dropdownType="DropdownType.instrument"></div>
가장 좋은 방법은 무엇입니까?
편집됨: 예제를 만들었습니다.
import {bootstrap} from 'angular2/platform/browser';
import {Component, View, Input} from 'angular2/core';
export enum DropdownType {
instrument = 0,
account = 1,
currency = 2
}
@Component({selector: '[.Dropdown]',})
@View({template: ''})
export class Dropdown {
public dropdownTypes = DropdownType;
@Input() public set dropdownType(value: any) {console.log(`-- dropdownType: ${value}`);};
constructor() {console.log('-- Dropdown ready --');}
}
@Component({ selector: 'header' })
@View({ template: '<div class="Dropdown" dropdownType="dropdownTypes.instrument"> </div>', directives: [Dropdown] })
class Header {}
@Component({ selector: 'my-app' })
@View({ template: '<header></header>', directives: [Header] })
class Tester {}
bootstrap(Tester);
다음을 작성합니다.Enum:
enum ACTIVE_OPTIONS {
HOME = 0,
USERS = 1,
PLAYERS = 2
}
구성 요소를 만듭니다. 열거 목록의 유형은 다음과 같습니다.
export class AppComponent {
ACTIVE_OPTIONS = ACTIVE_OPTIONS;
active: ACTIVE_OPTIONS;
}
템플릿 만들기:
<li [ngClass]="{ 'active': active === ACTIVE_OPTIONS.HOME }">
<a routerLink="/in">
<i class="fa fa-fw fa-dashboard"></i> Home
</a>
</li>
상위 구성 요소에 대한 열거형 속성을 구성 요소 클래스에 만들고 열거형을 할당한 다음 템플릿에서 해당 속성을 참조합니다.
export class Parent {
public dropdownTypes = DropdownType;
}
export class Dropdown {
@Input() public set dropdownType(value: any) {
console.log(value);
};
}
이렇게 하면 템플릿에서 예상한 대로 열거형을 열거할 수 있습니다.
<div class="Dropdown" [dropdownType]="dropdownTypes.instrument"></div>
Enum 이름을 가져오려는 경우:
export enum Gender {
Man = 1,
Woman = 2
}
구성 요소 파일에서
public gender: typeof Gender = Gender;
견본으로
<input [value]="gender.Man" />
아마도 당신은 이것을 할 필요가 없을 것입니다.
예를 들어, Numeric Enum:
export enum DropdownType {
instrument = 0,
account = 1,
currency = 2
}
HTML 템플릿에서:
<div class="Dropdown" [dropdownType]="1"></div>
결과:dropdownType == DropdownType.account
또는 String Enum:
export enum DropdownType {
instrument = "instrument",
account = "account",
currency = "currency"
}
<div class="Dropdown" [dropdownType]="'currency'"></div>
결과:dropdownType == DropdownType.currency
Enum 이름을 가져오려는 경우:
val enumValue = DropdownType.currency
DropdownType[enumValue] // print "currency", Even the "numeric enum" is also.
파티에 좀 늦었어요.
사용할 수 있습니다....set (value: keyof DropdownType)...
그런 식으로 함수는 열거형의 키로만 호출할 수 있습니다.
그런 다음 문자열 값을 열거형 값으로 변환하면 됩니다.이것은 TypeScript에서 직접 가능하지 않지만 해결 방법을 사용할 수 있습니다.
TS의 열거형은 다음과 같이 컴파일됩니다.
var DropdownType = {
instrument = 0,
account = 1,
currency = 2
};
Object.freeze(DropdownType);
컴파일 후 열거형이 불변 개체가 되므로 키의 이름을 인덱서로 사용할 수 있습니다.우리는 컴파일러 주변에서 작업하면 됩니다.
@Input() public set dropdownType(value: keyof DropdownType) {
const enumValue = (DropdownType as any)[value] as DropdownType;
console.log(enumValue);
};
그러나 열거형이 JS에 추가되면 더 이상 작동하지 않을 수 있습니다.그리고 우리는 컴파일러에 대해 작업하고 있기 때문에 발생하는 오류에 대해 경고하지 않습니다.
또한 IDE가 충분히 현명한 경우에만 자동 완성이 작동합니다.VSCode Workspace는 자동으로 완료되지 않지만 WebStorm은 자동으로 완료됩니다.
편집:
이런 식으로 열거형을 더 자주 사용한다면 프로젝트 어딘가에 정적 도우미 함수를 만들 것을 제안합니다.
function getValueFromEnum<T extends {[key: string]: string | number}>(
e: T,
key: keyof T
) {
return e[key];
}
언급URL : https://stackoverflow.com/questions/35923744/pass-enums-in-angular2-view-templates
'programing' 카테고리의 다른 글
| 함수의 반환 값을 다중 처리로 전달하는 방법.과정? (0) | 2023.04.29 |
|---|---|
| 이클립스(ADT)에서 APK 내보내기가 자동으로 충돌합니다. (0) | 2023.04.29 |
| WPF에서 제출 버튼을 만드는 방법은 무엇입니까? (0) | 2023.04.29 |
| STA 스레드에서 무언가를 실행하는 방법은 무엇입니까? (0) | 2023.04.29 |
| 클래스는 슈퍼클래스의 필수 멤버를 구현하지 않습니다. (0) | 2023.04.24 |