Passing subset of constant values to angular component

Viewed 581

I have the following constant defined in one of my models.

    export const NEWS_TYPE_TEXT = {
      News: 'News',
      Interview: 'Interview',
      Digest: 'Digest',
      CompanyAnalysis: 'Company Analysis',
    };

Usually I would pass the whole constant to the component, i.e.:

<mb-simple-select [options]="NEWS_TYPE_TEXT"> </mb-simple-select>

But now I need to pass only a subset of these values. (For example, only 'News' and 'Digest').

I have tried the following, which does not work:

<simple-select [options]="NEWS_TYPE_TEXT.News, NEWS_TYPE_TEXT.Digest"></simple-select>

Then I tried the following. This works, but passes the values as an array, and only the actual text values, without the keys:

<simple-select [options]="[NEWS_TYPE_TEXT.News, NEWS_TYPE_TEXT.Digest]"></simple-select>

Is there an elegant way to pass this subset of values to a component so that they preserve their object key:value structure?

Thanks in advance.

3 Answers

Try something like this:

<simple-select [options]="{News: NEWS_TYPE_TEXT.News, Digest: NEWS_TYPE_TEXT.Digest}"></simple-select>

I would suggest you define class for the required options and pass it.

i.e:

  1. Define class X for News, Digest
  2. Assign the values of X inside the ts
  3. Define @Input() to support X inside simple-select
  4. Pass the X to simple-select

I don't think there's a direct answer to the issue. You might have to create a quick pipe to produce an object containing only the properties you wish to have.

Try the following

pluck.pipe.ts

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: "pluck", pure: true })
export class PluckPipe implements PipeTransform {
  transform(value: {[key: string]: string}, args?: Array<string>): any {
    if (!value) return null;

    return args.reduce((acc, curr) => {
      acc[curr] = value[curr];
      return acc;
    }, Object.create(null));
  }
}

Usage

<simple-select [options]="NEWS_TYPE_TEXT | pluck:['News','Digest']"></simple-select>

Working example: Stackblitz


Pipe namesake is the RxJS pluck operator. Other than the name, it's completely unrelated to the issue at hand.

Related