Utilizing Ionic 2 with Typescript for executing forEach operations

I am in the process of migrating my AngularJS application to Angular 2. In my AngularJS controller, I had a JSON array that I was iterating through to display data in an accordion list. Now, I need to implement the same functionality in my Angular 2 component.

This is the code snippet from my AngularJS application:

myApp.factory('Plan', function() {

        var days = [
          { "id": 0,
            "name": 'Your Training Plan for Today',
            "exercises":[
                {"id":1,"name":'Best Stretch', "watchedToday": 'false', "type":"body"},
                {"id":8,"name":'Colors', "watchedToday": 'false', "type":"memory"},
                // More exercise items...
            ]
          }
        ];

        return {
          all: function() {
            return days;
          },
          get: function(dayId) {
            return days[dayId];
          }
        }

      });

     //In my controller
     $scope.days=Plan.all();
                    angular.forEach($scope.days, function(value1, key){
                        angular.forEach(value1.exercises, function(value2, key){
                            if(value2.id==game_type && $scope.today === current_date_memory){
                                value2.watchedToday=true;

                            }

                        });

                      });
    

I am looking for guidance on how to translate this logic into Angular 2 code.

In my Angular 2 component, I have started with:

export class ContactPage {

         days = [

          { "id": 0,
            "name": 'Your Training Plan for Today',
            "exercises":[
                {"id":1,"name":'Best Stretch', "watchedToday": 'false', "type":"body"},
                {"id":8,"name":'Colors', "watchedToday": 'false', "type":"memory"},
                // More exercise items...
            ]
          }

        ];

        constructor(public navCtrl: NavController) {
        }

    }
    

Answer №1

I made some changes to my component:

export class ContactPage {

    public daysList : any[];
    public selectedGroup;

    constructor(public navCtrl: NavController) {

        this.daysList= [

        { "id": 0,
        "name": 'Today’s Workout Plan',
        "exercises":[

        {"id":1,"name":'Best Stretch', "watchedToday": 'false', "type":"body"},
        {"id":8,"name":'Colors', "watchedToday": 'false', "type":"memory"},

        {"id":2,"name":'Butterfly reverse', "watchedToday": 'false', "type":"body"},
        {"id":9,"name":'Precise Reaction', "watchedToday": 'false', "type":"memory"},

        {"id":3,"name":'SquatRow', "watchedToday": 'false', "type":"body"},
        {"id":10,"name":'Letting Go', "watchedToday": 'false', "type":"memory"},

        // {"id":13,"name":'Word Pairs 1', "watchedToday": 'false', "type":"memory"},
        {"id":4,"name":'Plank', "watchedToday": 'false', "type":"body"},
        {"id":11,"name":'Word Pairs', "watchedToday": 'false', "type":"memory"}, 

        {"id":5,"name":'Push Up', "watchedToday": 'false', "type":"body"},
        {"id":12,"name":'Vocabulary', "watchedToday": 'false', "type":"memory"},

        // {"id":14,"name":'Vocabulary 1', "watchedToday": 'false', "type":"memory"}, 
        {"id":6,"name":'Side Plank', "watchedToday": 'false', "type":"body"}, 
        {"id":7,"name":'Squat', "watchedToday": 'false', "type":"memory"}
        
        ]
    }

    ];

    this.daysList.forEach((value1, key) =>{


        value1.exercises.forEach((value2) =>{

        })
    });
}

    toggleGroup(group: any){

        if(this.isGroupSelected(group)){
            this.selectedGroup=null
        }
        else
        {
            this.selectedGroup=group

        }
    }

    isGroupSelected(group){

        return this.selectedGroup==group;

    }
}

and here is the updated template:

  <ion-list>

    <div *ngFor="let day of daysList"><br>
      <div class="item item-icon-left" (click)="toggleGroup(day)" [ngClass]="{active: isGroupSelected(day)}">
         <ion-icon name="isGroupSelected(day) ? 'remove' : 'add'"></ion-icon>
        {{day.name}}

      </div>

       <a class="item item-icon-left item-accordion" [hidden]="!isGroupSelected(day)" *ngFor="let exercise of day.exercises" 
           href="#">
          {{exercise.name}}

        </a>

  </div>
</ion-list>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Type definitions in Typescript for the style property of Animated.View

One of my components has a Props interface that extends ViewProps from React Native, like this: export interface Props extends ViewProps { // Custom props } As a result, this also extends the style prop. However, I am facing an issue while using Animat ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

The JSON object, which has been converted into a string and sent over the network,

Attempting to set up a websocket server using TypeScript in Node.js, the following code was used: ws.on('message', (msg: string) => { console.log("got message:" + msg); const m = JSON.parse(msg); console.log(m); ...

Is it possible to enforce strict typing for a property within an object that is declared as type 'any'?

In my code, I am dealing with a parent object of type 'any' that remains constant and cannot be changed. Within this context, I need to define a property for the parent object, but no matter what I try, it always ends up being loosely typed as &a ...

Encountering a situation where d3.events is returning null within Angular 2 TypeScript code

Seeking to enhance my d3 maps with tooltips, I came across a helpful code snippet at this link However, upon implementing the same code in an Angular 2 TypeScript file, an error emerged: Error: Cannot read property 'transition' of undefined Th ...

How can you define a function type for a rest parameter in Typescript?

At this point, I have a function that takes in two parameters: param 'a' as a string and 'b' as a function that returns a string. My intention is to call it using a rest parameter and specify the types accordingly. However, on line 10 ...

Can someone show me how to properly set up nested child routes in Angular 2?

My application structure is organized as shown below . ├── photos ├── posts ├── users │   ├── detail │   │   ├── address │   │   ├── family │   │   ├── information │   │   └ ...

Transferring properties to components within ng-content (attributes that are not accessible in the component where the code is located)

I am in the process of creating a carousel. The goal is for the developer to simply write all the markup in one place (let's say in app.component.html) with just an options property, and then have the carousel take control. The issue lies in the fac ...

Anticipated outcome is the need to provide a value upon completion of arrow function recursion (consistent-return)

If I have a recursive function like the example provided, is it possible to simply return false after the recursive foo call? function foo(fn, redo, interval = 1000) { return new Promise( (resolve, reject) => { fn() .then(resolve) ...

Using the Async feature, I can retrieve the value of a string type when the return type of a function is Promise<any>

While working on a custom pipe, I encountered a situation that puzzled me. Can you explain why the code snippet below is considered valid? async transform(value: any): Promise<string> { let fullNameBasedOnPreference: string; fullNameBasedOnP ...

Sorting an array of objects in TypeScript may result in a type error

My data includes various categories, ages, and countries... const data = [ { category: 'Fish', age: 10, country: 'United Kingdom' }, { category: 'Fish', age: 9, country: 'United Kingdom' }, { category: ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Cypress automation script fails to trigger Knockout computed subscription

Within my setup, I have implemented two textboxes and a span to display the result. Date: <input data-bind="value: dateValue"/> Number: <input data-bind="value: dateValue"/> Result : <span data-bind="text: calculatedValue">Result Should ...

In order for Angular jQuery click events to properly function, they must be triggered by a

My admin panel is built using jQuery and Bootstrap, and it functions properly when used outside of the Angular framework. However, after integrating jQuery and Bootstrap into an Angular project and configuring them, I noticed that I had to double click on ...

Unable to retrieve data from database using Angular 4

I am currently working with Angular 4 and using a MySQL database. This is my service: service.ts getData(){ return this.http.get('http://example/users.php').map(res=>{ return res.json(); }).catch(err=>{ return err.jso ...

Guide to manually triggering a re-render of a component in Angular 2

While working with ng Smarttable, I encountered a situation where I needed to change the datasource array through an event, specifically by altering an ID within the array. Strangely, Angular did not detect these changes until I interacted with the page by ...

FirebaseError: Trigger parsing error: Module 'grpc' not found

I'm currently working on setting up an Angular4 application with Server Side Rendering (SSR) using Angular Universal and Firebase Cloud Functions. While the application works smoothly with ng serve, I encountered an issue after building the app and s ...

Is there a way to assign values of object properties to the corresponding object in TypeScript?

I'm looking for a solution in TypeScript where I can map values of object keys to the same object, and have IntelliSense work correctly. Here's an example that illustrates what I need: const obj = getByName([ { __name: 'foo', baz: &ap ...

Troubleshooting: Why is my Angular Ionic Reactive Form not showing up on the

I'm currently experiencing an issue with my Angular/Ionic form, where the form controls are not displaying correctly on the web. My goal is to create a dynamic form that allows users to input the number of groups and students for each year. However, w ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...