Learn AspNet
Learn AspNet

Reputation: 1612

Pass the name of the object property in the HTML in angular template

Hi I have a html where I need to pass the object name/string in the html. For example:

HTML

<app-family
(callDad) ="callFamily($event, {{family.Dad}})""   // I want to pass "Dad" as a string
(callSon) ="callFamily($event, {{family.Son}})""   // I want to pass "Son" as a string but get it from the object so it is not error prone
(callMom) ="callFamily($event, {{family.Mom}})"" // I want to pass "Mom" as a string 
(callDaughter) ="callFamily($event, {{family.Daughter}})"" // I want to pass "Daugher" as a string 
></app-customer>

Component Class

export class Family  {
  family: Family;
}

Model

export class Family{
  Dad: string
  Mom: string
  Son: string
  Daughter: string
}

I want to get the name of the property and pass it in the html. Like Dad, mom, son and daughter?

Upvotes: 0

Views: 1092

Answers (2)

oz1985oz
oz1985oz

Reputation: 417

I think what you're trying to do is enum.

Model:

export enum Family {
  Dad = 'Dad',
  Mom = 'Mom',
  Son = 'Son',
  Daughter = 'Daughter',
}

In the ts component you need to import ’Family’:

family = Family;

In the HTML component:

callFamily($event, family.Dad)

Upvotes: 1

Srijon Chakraborty
Srijon Chakraborty

Reputation: 2154

I think have solution for you. Please check and try my code and the given stackblitz demo link =>
HTML:

<app-family
(callDad) ="callFamily($event, showPropName(family,family.Dad))"
(callSon) ="callFamily($event, showPropName(family,family.Son))"
(callMom) ="callFamily($event, showPropName(family,family.Mom))"
(callDaughter) ="callFamily($event, showPropName(family,family.Daughter))"
></app-family>

TS:

showPropName(property, value)
{
    for(var i in property)
    {
        if (property[i] == value)
        {
            return i;
        }
    }
    return false;
}

Demo Link => Stackblitz. Demo link contains 2 button. On button click property name is displayed in the console.
So, I think using this process you can pass property name to any method.

Upvotes: 1

Related Questions