0

I want to setup a reusable dropdown menu whereby I pass an array of objecs to the @Input of my dropdown component and then update some labels in it.

The array fields will be different each time. One array might have a displayName string field, while another array will have a string called id as the field I want to reference, for example.

I'm not sure how to reference these on a per instance basis.

Dropdown HTML:

<ng-container *ngFor="let item of content">
  <span class="button-label">{{item.whatever-the-field-is}}</span>
</ng-container>

Dropdown Component:

@Input() content: Array<any> = [];

Dropdown Instance:

<multi-button-dropdown [content]="(myArrayObservable$ | async)"></multi-button-dropdown>

Example Arrays:

users = [
  {
    id: 'afvnf102841-251',
    username: 'Joe Bloggs'
  }
  ...
]

members = [
  {
    displayName: 'Han Solo',
    location: 'Space'
  }
  ...
]

Question:

How do i setup the dropdown.html/component so that the <span> {{item....}} reference will be displayName for the members[] instance, id for the users[] instance and so on, passed in by another @Input value?

2
  • 1
    The example arrays are wrong. Probably you were trying to define array of objects instead. Commented Mar 26, 2021 at 11:01
  • Thanks, I missed that completely Commented Mar 26, 2021 at 11:14

2 Answers 2

1

One quick way would be to use the keyvalue pipe inside the *ngFor to iterate over the object properties without knowing it's names.

<ng-container *ngFor="let item of content">
  <span class="button-label" *ngFor="let prop of item | keyvalue">
    {{ prop.key }} - {{ prop.value }}
  </span>
</ng-container>
Sign up to request clarification or add additional context in comments.

Comments

0

I figured out that I can make a new interface which sets out the label value, and map the Observable array object fields to this value before passing it into the component:

this.dropdownUsers = users.map(user => (
  {
    label: user.displayName
  }
));

<multi-button-dropdown [content]="dropdownUsers"></multi-button-dropdown>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.