[英]Angular5: Iterate Over Enum Using *ngFor
I am trying to make a structure of some sort that has key value pairs where the key is an identifier like 'equals' and the values are the unicode equivalent html like '\='.<\/i>我正在尝试创建某种具有键值对的结构,其中键是像'equals'这样的标识符,而值是像'\='这样的unicode等效html。<\/b> Right now I am using an enum, but I am not sure if this is the best structure.<\/i>现在我正在使用枚举,但我不确定这是否是最好的结构。<\/b> Anyways, I need to use this enum (or other structure) to display the unicode characters in a drop down on a page by using a ngFor statement to iterate over my enum and making options which innerHtml correspondes to the unicode character.<\/i>无论如何,我需要使用这个枚举(或其他结构)通过使用 ngFor 语句迭代我的枚举并设置 innerHtml 对应于 unicode 字符的选项,从而在页面的下拉菜单中显示 unicode 字符。<\/b> What is the best way to do this?<\/i>做这个的最好方式是什么?<\/b><\/p>
Right now my code is as follows:<\/i>现在我的代码如下:<\/b><\/p>
enum<\/strong><\/i>枚举<\/strong><\/b><\/p>
export enum Symbols {
equals = '\u003D'
}
To have the enum accessible within the component, you must declare a property, like you did, but instead of declaring it of type<\/em> Symbols<\/code> (using
:<\/code> ), you should assign
Symbol<\/code> to it (using
=<\/code> ).<\/i>
要在组件中访问枚举,您必须声明一个属性,就像您所做的那样,但不是将其声明为
Symbols<\/code>类型<\/em>(使用
:<\/code> ),您应该将
Symbol<\/code>分配给它(使用
=<\/code> )。<\/b><\/p>
To declare a
<select><\/code> with options, you should use the
*ngFor<\/code> in the
<option><\/code> s, not in the
<select><\/code> .<\/i>要声明带有选项的
<select><\/code> ,您应该在
<option><\/code>中使用
*ngFor<\/code> ,而不是在
<select><\/code>中。<\/b><\/p>
Also, to iterate the enum, you must use
Object.keys(symbols)<\/code> , which is aliased by
keys(symbol)<\/code> in the template below.<\/i>此外,要迭代枚举,您必须使用
Object.keys(symbols)<\/code> ,它在下面的模板中由
keys(symbol)<\/code>别名。<\/b><\/p>
Stackblitz Demo here.<\/strong><\/a><\/i>
Stackblitz 演示在这里。<\/strong><\/a><\/b><\/p>
import { Component } from '@angular/core';
export enum Symbols {
equals = '\u003D',
notEquals = '!='
}
@Component({
selector: 'my-app',
template: `
<p>
Having the name as label and symbol as value:
<select>
<option *ngFor="let symbol of keys(symbols)" [ngValue]="symbols[symbol]">{{symbol}}</option>
</select>
</p>
<p>
Having the symbol as label and name as value:
<select>
<option *ngFor="let symbol of keys(symbols)" [ngValue]="symbol">{{symbols[symbol]}}</option>
</select>
</p>
`
})
export class AppComponent {
keys = Object.keys;
symbols = Symbols;
}
You can also use the keyvalue pipe as well, it makes your life easier.你也可以使用 keyvalue 管道,它让你的生活更轻松。
<p *ngFor="let enum of TestEnum | keyvalue">
{{ enum.key }} - {{ enum.value}}
</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.