K
K
kachurinets2018-11-02 12:25:14
JavaScript
kachurinets, 2018-11-02 12:25:14

How to properly write logic in *ngFor?

I have an object in which each property is an object.

objectKeys = Object.keys;
tableColumnsConfig: any = {
        id: {
            name: 'ID',
            value: true
        },
        title: {
            name: 'Застройщик',
            value: true
        },
        phone: {
            name: 'Телефон',
            value: true
        },
        website: {
            name: 'URL',
            value: false
        },
        avitoId: {
            name: 'Avito ID',
            value: true
        }
}

I list the field names like this
<div *ngFor="let key of objectKeys(tableColumnsConfig)">
{{tableColumnsConfig[key].name}}
</div>

How can I make sure that those values ​​\u200b\u200bthat have value === false do not fall into this list?
ps In my case, it is impossible to transfer an object to an array of objects. It is also impossible to create an additional array, you need to use only the tableColumnsConfig object

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Mazhekin, 2018-11-02
@kachurinets

<div *ngFor="let column of tableColumnsConfig | toIterable | trueOnlyBy : 'value'">
   {{column.name}}
</div>

and write two common pipes, maybe they will come in handy later, somewhere in a shared module like shared.module.ts
1) to-iterable.pipe.ts
@Pipe({
  name: 'toIterable'
})
export class ToIterablePipe implements PipeTransform {
  transform(dict: Object) {
    return Object.keys(dict || {}).map(key => dict[key]);
  }
}

2) true-only-by.pipe.ts
@Pipe({
  name: 'trueOnlyBy'
})
export class TrueOnlyByPipe implements PipeTransform {
  transform(arr: any[], propName: string): object {
    return arr.filter(item => !!item[propName]);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question