【问题标题】:convert value to label under angular primeng在 angular primeng 下将值转换为标签
【发布时间】:2020-06-25 07:17:01
【问题描述】:

你能帮我一个忙吗?

环境是angular9和primeng。

我有两页。

  1. 显示详细信息。
  2. 编辑/创建。

2.具有 p-dropdown 组件。这工作正常。

1.是问题。我可以显示值但不能显示标签。 我尝试如下。这不起作用。

{{types[info.type].label}}

列表是这样定义的。 x.component.ts

readonly types: SelectItem[] = [
    { label: '---', value: null }, //index=0
    { label: 'a', value: '0' }, //index=1
    { label: 'b', value: '1' }, //index=2
    { label: 'c', value: '2' }, //index=3
];

如果 info.type = 1, 正确答案是'b',但它返回'a'。

types[info.type].label //

如何从值中搜索列表? 我的头像是这样的。

类型[值-> info.type].label

类型['' + info.type].label

这些当然是行不通的。 我的页面中有 350 个下拉菜单,所以如果可能的话,不要在 component.ts 中编写转换代码。

【问题讨论】:

  • 您能否说明info 是如何定义的?

标签: angular typescript primeng


【解决方案1】:

在 p-dropdown 中使用 optionLabel 和 json 中的键,您要显示。

<p-dropdown  optionLabel="label" name="type" [options]="types" [(ngModel)]="info.type"></p-dropdown>

【讨论】:

  • 感谢您的回复。下拉菜单工作正常。问题是标签(简单文本)而不是下拉菜单。 //
  • 如果我的回答对你有用,请采纳。
【解决方案2】:

从您提供的有限信息来看,label: '---' 似乎在弄乱数组索引。换个试试

{{ types[info.type].label }}

{{ types[info.type + 1]?.label }}

Safe navigation operator ?. 还用于验证是否在尝试访问其属性 label 之前定义了 types[info.type - 1]

【讨论】:

  • 感谢您的回复。看起来不错的主意,但不能解决问题。因为没有人能保证这份清单在未来不会改变。例如,如果列表更改为:readonly types: SelectItem[] = [ { label: '---', value: null }, //index=0 { label: 'a', value: '0' } , //index=1 { label: 'a+', value: '3'}, //index=2 { label: 'b', value: '1' }, //index=3 { label: 'c' , value: '2' }, //index=4 ];列表中的数据已经不多了。因此,无法将数据作为索引保存到数据库中。必须节省价值。
【解决方案3】:

现在,我找到了解决方案。 这个解决方案与我的要求有点不同。 但这是工作。

我制作新组件并添加代码。

component.html

 {{ label }}

组件.ts

@Component({
  selector: 'app-listlabel',
  templateUrl: './listlabel.component.html',
  styleUrls: ['./listlabel.component.css']
})
export class ListlabelComponent implements OnInit {
    @Input() list: SelectItem[];
    @Input() value: string;   
    public label: string;

    ngOnChanges(): void {
        this.label = this.list.filter(item => item.value == this.value)[0].label;   
    }
}

mother.html

<app-listlabel [value]="info.type" [list]="types"></app-listlabel>

谢谢大家!

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2012-10-04
    • 2023-01-11
    相关资源
    最近更新 更多