简体   繁体   中英

Angular 5 make local variable to global

I have a code like this :

var data = [
   {
     first_name: "Apurv",
     date: "2018-01-22",
     is_present: "1", 
   },
   {
     first_name: "Lucky",
     date: "2018-01-22",
     is_present: "0", 
   },
   {
     first_name: "Apurv",
     date: "2018-01-20",
     is_present: "0", 
   },
   {
     first_name: "Lucky",
     date: "2018-01-20",
     is_present: "1", 
   }
];

var groupByName = {};

data.forEach(function (a) {
    groupByName [a.first_name] = groupByName [a.first_name] || [];
    groupByName [a.first_name].push({ date: a.date, is_present: a.is_present });
});

console.log(groupByName);

I try to make local variable of groupByName variable become global in order to works with *ngIf on Angular 5, could everyone clearing this or maybe there is another way to solve this issue? I would be thank you before!

You should do it as a property of your component :

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-mycomponent',
  template: '<some html here>',
})
export class MyComponent implements OnInit{

  public data:any[];
  public groupByName:any;


  ngOnInit() {
    this.data = [
       {
         first_name: "Apurv",
         date: "2018-01-22",
         is_present: "1", 
       },
       {
         first_name: "Lucky",
         date: "2018-01-22",
         is_present: "0", 
       },
       {
         first_name: "Apurv",
         date: "2018-01-20",
         is_present: "0", 
       },
       {
         first_name: "Lucky",
         date: "2018-01-20",
         is_present: "1", 
       }
    ];

    this.groupByName = {};

    this.data.forEach(function (a) {
        this.groupByName[a.first_name] = this.groupByName [a.first_name] || [];
        this.groupByName[a.first_name].push({ date: a.date, is_present: a.is_present });
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM