1

I am trying to fill an array with custom objects. The icon property is optional and when it's not provided it must use a default value.

class type:

export class Shortcut {
  text: string;
  icon?: string = 'fa-external-link';
}

typescript dashoard component

export class DashboardComponent implements OnInit {
  shortcutList: Shortcut[] = [];

  ngOnInit() {
    this.getShortcuts();
  }

  getShortcuts(): void {
    this.shortcutList = [
      { text: 'shortcut 001'}
      { text: 'shortcut 002', icon: 'fa-users' }
    ];
  }
}

The default icon in the first record is missing. I tried it with a constructor but I didn't work for me.

1
  • 1
    Because your Shortcut is a class that you never instanciate in your shortcutList. It defaults to behave like an interface (that cannot have default field value). Commented Jun 29, 2021 at 9:41

1 Answer 1

2

You can use a ternary in the html file.

<img [src]="shortcut.image ? shortcut.image : 'link to your image'" />

Or you can use the ngClass for icons

<i [ngClass]="shortcut.icon ? shortcut.icon : 'fas fa-cloud'"></i>

You can also do this same in the ts file

  shortcutList: Shortcut[] = [];
  defaultIcon: string = 'fas fa-cloud';

  ngOnInit() {
    this.getShortcuts();
  }

  getShortcuts(): void {
    this.shortcutList = [
      { text: 'shortcut 001', icon: this.defaultIcon }
      { text: 'shortcut 002', icon: 'fa-users' }
    ];
  }

if your data is coming from an Api

...your api returns an array i.e repsonse 
response.map(item => {
  item.icon = item.icon ? item.icon : 'fas fa-cloud',
  ... you can add other conditions as well.
})
Sign up to request clarification or add additional context in comments.

5 Comments

That is a solution I have for now. But i don't see this as the answer because I need a few more properties and if need to check them all in the html it will be a mess.
You can map the default values in the ts file if you don’t want to handle in the html. When you get the data from the api. You need to map them with default values. This is the other way you can handle
Data is hardcoded in the component. I am not getting this data from an api.
Then you can add it in the json itself right? You can store that icon value as a global variable and assign that to the icon key.
Thanks for the replies. I mapped the other default properties and kept the icon with a tenary. I used this answer for an example: stackoverflow.com/questions/45289770/…

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.