0

I'm trying to create a nested array in my angular 9 component so I can call it in the template. I'm not sure whether the problem is formatting or if there is something I'm doing fundamentally wrong. I keep getting this error msg: Cannot read property 'push' of undefined

Here is my typescript:

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

@Component({
  selector: 'ngx-analysis',
  templateUrl: './analysis.component.html',
  styleUrls: ['./analysis.component.scss']
})
export class AnalysisComponent implements OnInit {

    persuadables: [{'icon':string, 'desc':string, 'status':string}];

    constructor() { }

    ngOnInit() {
        this.persuadablePush();
    }

significance(score, name, arr){

        if (score == 1.0){
            arr.push({'icon':'checkmark-done-circle', 'desc': 'Very ' + name.toLowerCase(), 'status':'success'}) ;
        }
        else if (score == 0.5){
            arr.push({'icon':'checkmark-circle', 'desc':name, 'status':'info'}) ;
 
        }
        else if (score == 0.0){
            arr.push({'icon':'close-circle', 'desc': 'Not ' + name.toLowerCase(), 'status':'danger'}) ;

        }
    }
persuadablePush(){

        for( let i=5; i<10; i++ ){

            this.significance(
                this.insights['consumption_preferences'][0]['consumption_preferences'][i]['score'],// =number
                this.insights['consumption_preferences'][0]['consumption_preferences'][i]['name'],// =string
                this.persuadables
            )
        }
    }

and here's my HTML:

<nb-card size="small">
      <nb-card-header>Persuadables</nb-card-header>
      <nb-card-body>
        <nb-list *ngFor='let obj of persuadables'>
            <nb-icon icon='obj.icon' status='obj.status'></nb-icon>
            {{obj.desc}}
        </nb-list>
      </nb-card-body>
    </nb-card>

Thank you for your help!

0

2 Answers 2

1

I think what you are looking for is (either should work)

export class AnalysisComponent implements OnInit {
    //persuadables: Array<{'icon':string, 'desc':string, 'status':string}> = [];
    //persuadables: {'icon':string, 'desc':string, 'status':string}[] = [];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That was indeed the issue.
0

I think that happened cause you wrote the type but you not defined array.

Try like this:

export interface Persuadable {
  icon: string;
  desc: string;
  status: string;
}
export class AnalysisComponent implements OnInit {
    public persuadables: Array<Persuadable> = [];
}

Use interfaces and init your array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.