Search code examples
jsonangulartypescriptfrontendangular6

Using ng-repeat or ngFor to display each object in a JSON object as individual list items


I recieve an object that looks like this: enter image description here

I'm trying to use ng-repeat to display the "Message", "Priority" and "DateTime" properties of each object as li items in a ul.

I've tried a couple of approaches including ng-repeat and ngFor, where all have been wrapped in divs like the first option:

  1. This seems like the proper way to do it, but returns exactly nothing:

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

  2. This option returns the specific object as expected:

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

  3. Doesnt compile:

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

My TS looks like this:

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
  }
}

Solution

  • Using angular you should forget ng-repeat that is apart of AngularJS (version <= 1.6)

    I think you have a double problem, the first one, as said, is ng-repeat, the second one is that you are not well targeting your data.

    Try this

    template

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