0
votes

Could you do me a favor?

environment is angular9 and primeng.

I have two pages.

  1. show detail.
  2. edit/create.

2.has p-dropdown component. this is working fine.

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

1.is problem. i can display value but not label. I tried as follow. this is not working.

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

List is defined like this. 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
];

if info.type = 1, right answer is 'b' but it returned 'a'.

types[info.type].label // <-this is recognized as index, not value.

How to search list from value? My image is like this.

types[value -> info.type].label

or

types['' + info.type].label

ofcourse these are not work. I have 350 dropdowns in my page, so if possible, do not want to write convert code in component.ts.

3
Could you please show how info is defined?Michael D

3 Answers

1
votes

Use optionLabel in the p-dropdown with the key from json, you want to display.

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

From the limited information you've provided, it seems the label: '---' is messing with the array index. Try replacing

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

with

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

Safe navigation operator ?. is also used to verify if types[info.type - 1] is defined before trying to access it's property label.

0
votes

now, i found the solution. this solution is bit different from my request. but it is work.

i make new component and add code to it.

component.html

 {{ label }}

component.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>

Thanks everyone!