Josh
Josh

Reputation: 3100

Method in Angular2 template binding

I'm trying to return the category name as a string in a template of a component. The method is stored in the provider for the given data model.

For example:

     <div class="category">
            {{ vendorProvider.getCategoryName(vendor.category_id) }}
        </div>

And in the provider:

  getCategoryName(id) {
        return this.vendorCategories.find((x => x.id === id)).name;
    }

But I sometimes get errors such as 'Could not read property 'name' of undefined' when manipulating the vendor variable, say, in an edit form. What is the proper way to use a method in an Angular template binding? Or how else can I retrieve the category name from a array variable with a provided category ID?

Upvotes: 0

Views: 928

Answers (1)

user1533603
user1533603

Reputation: 329

You could just return the object from function and then use safe navigation operator in template

getCategoryName(id) {
     return this.vendorCategories.find((x => x.id === id));
}

in template

{{ vendorProvider.getCategoryName(vendor.category_id)?.name }}

Upvotes: 1

Related Questions