【问题标题】:Pass the name of the object property in the HTML in angular template在 Angular 模板中传递 HTML 中对象属性的名称
【发布时间】:2021-02-13 09:46:20
【问题描述】:

嗨,我有一个 html,我需要在 html 中传递对象名称/字符串。例如:

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>

组件类

export class Family  {
  family: Family;
}

型号

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

我想获取属性的名称并在 html 中传递它。像爸爸、妈妈、儿子和女儿一样?

【问题讨论】:

标签: angular typescript


【解决方案1】:

我想有适合你的解决方案。请检查并尝试我的代码和给定的 stackblitz 演示链接 =>
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;
}

演示链接 => Stackblitz。演示链接包含 2 个按钮。按钮单击属性名称显示在控制台中。
所以,我认为使用这个过程,您可以将属性名称传递给任何方法。

【讨论】:

    【解决方案2】:

    我认为你想要做的是enum

    型号:

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

    在ts组件中需要导入‘Family’:

    family = Family;
    

    在 HTML 组件中:

    callFamily($event, family.Dad)
    

    【讨论】:

      猜你喜欢
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 2017-01-31
      • 2016-01-16
      • 2011-09-20
      • 1970-01-01
      相关资源
      最近更新 更多