【问题标题】:Using ng-repeat or ngFor to display each object in a JSON object as individual list items使用 ng-repeat 或 ngFor 将 JSON 对象中的每个对象显示为单独的列表项
【发布时间】:2018-12-02 02:21:09
【问题描述】:

我收到一个如下所示的对象:

我正在尝试使用 ng-repeat 将每个对象的“消息”、“优先级”和“日期时间”属性显示为 ul 中的 li 项。

我尝试了几种方法,包括 ng-repeat 和 ngFor,它们都像第一个选项一样被包裹在 div 中:

  1. 这似乎是正确的做法,但什么也不返回:

    <div style="background: red;"> <ul> <li ng-repeat="Notification in allNotifications">{{Notification}}</li> </ul> </div>

  2. 此选项按预期返回特定对象:

    <li style="border-radius: 3px" [ngStyle]="{'color' : alertText}" > Notification: {{ allNotifications.Notifications['0'].Message['0'] }} </li>

  3. 无法编译:

    <li style="border-radius: 3px" [ngStyle]="{'color' : alertText}" [ngFor]="let subItem of allNotifications.Notifications['0'].Message['0']"> Notification: {{ subItem }} </li>

我的 TS 是这样的:

export class EventLogComponent implements OnInit {

  constructor(private _dashdata: DashdataService) { }

  NotificationName: string;
  alertText: string;
  allNotifications: JSON;

  ngOnInit() {
    this.NotificationName = 'NoNameAvailable';
    this.alertText = 'Black'; //TODO: set color according to threatlevel

    setInterval(() => {
      this._dashdata.getAllNotifications()
        .subscribe(res => {
          this.allNotifications = res['notificationdata'];
          console.log(this.allNotifications);
        });
    }, 5000); // Data Update interval in MS
  }
}

【问题讨论】:

标签: json angular typescript frontend angular6


【解决方案1】:

使用 Angular 你应该忘记 ng-repeat 是 AngularJS 的一部分(版本

我认为你有一个双重问题,第一个问题,如上所述,是 ng-repeat,第二个问题是你没有很好地定位你的数据。

试试这个

模板

<div style="background: red;">
  <ul>
    <li *ngFor="let not of allNotifications.Notification">{{not}}</li>
  </ul>
</div>

【讨论】:

    【解决方案2】:

    ng-repeat 是框架 AngularJS 的指令。

    您正在使用 Angular,所以在您的情况下,您应该使用 ngFor:
    &lt;div style="background: red;"&gt; &lt;ul&gt; &lt;li *ngFor="let notification of allNotifications"&gt;{{notification}}&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      相关资源
      最近更新 更多