'Cannot access Enum in Angular template
My purpose is use the enum to read a array's property. This code gives me error:
<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>
StudentEnum is a enum class, but if i put in the template it doesn't work. What is the correct method to read array properties and values using a enum in a template?
{{ elem[StudentEnum.name] }}
Solution 1:[1]
The variables referenced using the interpolation syntax {{ }} is scoped within the corresponding component's class. It has no access to variable like StudentEnum that's defined outside this class' scope.
Option 1: Local member variable
You could create a local member variable to hold the enum. Here is an illustration:
import { StudentEnum } from './model/student.enum.ts';
@Component({...})
export class SomeComponent implements OnInit {
public studentEnum = StudentEnum; // <-- assign the enum to a member variable
...
}
<!-- Notice the small `s` in `studentEnum`. It's referring to the member variable -->
<input type="text" pInputText value="{{elem[studentEnum.name] }}" name="student_name"/>
Option 2: Pipe
If you do not wish to create a local member variable for each component where the enum is used, you could create a pipe to return the corresponding value.
For example
student.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];
}
}
And use it in the template
<input type="text" pInputText value="{{elem['name' | student] }}" name="student_name"/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
