poo*_*opp 5 enums typescript angular2-template angular
我的目的是使用枚举来读取数组的属性。这段代码给我错误:
<ng-container *ngFor="let elem of list">
<div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-12 ui-xl-12">
<div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-3 ui-xl-3">
<input type="text" pInputText value="{{elem[StudentEnum.name] }}" name="student_name" />
</div>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
StudentEnum是一个枚举类,但是如果我放入模板中它就不起作用。在模板中使用枚举读取数组属性和值的正确方法是什么?
{{ elem[StudentEnum.name] }}
Run Code Online (Sandbox Code Playgroud)
使用插值语法引用的变量的范围{{ }}位于相应组件的类内。它无法访问StudentEnum在此类范围之外定义的变量。
您可以创建一个本地成员变量来保存枚举。这是一个例子:
import { StudentEnum } from './model/student.enum.ts';
@Component({...})
export class SomeComponent implements OnInit {
public studentEnum = StudentEnum; // <-- assign the enum to a member variable
...
}
Run Code Online (Sandbox Code Playgroud)
<!-- Notice the small `s` in `studentEnum`. It's referring to the member variable -->
<input type="text" pInputText value="{{elem[studentEnum.name] }}" name="student_name"/>
Run Code Online (Sandbox Code Playgroud)
如果您不希望为使用枚举的每个组件创建本地成员变量,则可以创建一个管道来返回相应的值。
例如
学生.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { StudentEnum } from './model/student.enum.ts';
@Pipe({
name: 'student',
pure: true,
})
export class StudentPipe implements PipeTransform {
transform(value: any): any {
if (!value) {
return null;
}
return StudentEnum[value];
}
}
Run Code Online (Sandbox Code Playgroud)
并在模板中使用它
<input type="text" pInputText value="{{elem['name' | student] }}" name="student_name"/>
Run Code Online (Sandbox Code Playgroud)