【问题标题】:Key value from variable and string in Angular TemplateAngular模板中变量和字符串的键值
【发布时间】:2022-02-02 16:57:54
【问题描述】:

有没有办法从字符串中组合打字稿中对象的键值?这是一个例子:

object[index].key=value

应该是,

object[index].["String".array[i]]=value

以下不起作用:

{{ object[index].{{"string".concat(Variable[index])}} }} <-- the rendering is perfectly fine but the execution is missing

我正在尝试在两个“ngFor”循环中读取一个对象,第一个循环充当数组的计数器,该数组的元素充当第二个循环中对象的键。

谢谢

编辑:

tage=['Montag','Dienstag','Mittwoch']
  
  objectArray: {
    id:Number;
    name:String;
    Montag:String;
    Dienstag:String;
    Mittwoch:String;
  }[]=[
    {id:0,name:'Klaus',Montag:'arbeiten',Dienstag:'rumgammeln',Mittwoch:'Frei'},
    {id:1,name:'Dieter',Montag:'frei',Dienstag:'arbeiten',Mittwoch:'rumgammeln'},
    {id:2,name:'Peter',Montag:'rumgammeln',Dienstag:'frei',Mittwoch:'arbeiten'},
  ]

模板

1:{{objectArray[0].Montag}}<br>

2:{{objectArray[0]['Montag']}}<br>

<br>

<ng-container *ngFor="let tag of tage; let i=index">
  {{i}}:{{objectArray[0][tage[i]]}}<br> <------- NOT WORKING
</ng-container>

错误信息

(property) AppComponent.tage: string[]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ id: Number; name: String; Montag: String; Dienstag: String; Mittwoch: String; }'.
  No index signature with a parameter of type 'string' was found on type '{ id: Number; name: String; Montag: String; Dienstag: String; Mittwoch: String; }'.ngtsc(7053)
app.component.ts(8, 53): Error occurs in the template of component AppComponent.

【问题讨论】:

标签: arrays angular string object templates


【解决方案1】:

我认为您正在寻找keyvalue 管道,它可以让您在模板中访问对象的键/值。 https://angular.io/api/common/KeyValuePipe

  testObject: { [key: number]: string } =
  {
    1: 'Object Value 1',
    2: 'Object Value 2',
    3: 'Object Value 3'
  };

  testMap = new Map([
    [2, 'Map Value 2'],
    [null, 'Map Value 3'],
    [1, 'Map Value 1'],
  ]);

  arrTest = ["Array Item 1",
    "Array Item 2",
    "Array Item 3"]
<p>Object & KeyValue Pipe</p>
<div *ngFor="let item of testObject | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>


<p>Maps & KeyValue Pipe</p>
<div *ngFor="let item of testMap | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

<p>Arrays & KeyValue Pipe</p>
<div *ngFor="let item of arrTest | keyvalue:descOrder">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

示例:https://stackblitz.com/edit/angular-key-value-pipe-demo-kphrro?file=src%2Fapp%2Fapp.component.html

【讨论】:

  • 我正在尝试使用 arrTest 的一个值作为 testObject 的键来获取相关的 testObjects 值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 2011-04-13
  • 2020-04-06
相关资源
最近更新 更多