Roberto Mejia
Roberto Mejia

Reputation: 73

How can I display my json object with TypeScript in Angular?

I am trying to display my json array in html using *ngFor but I believe it's not working because it needs to be inside the class AppComponent. But if I try to move the source code to make the json object inside the AppComponent class I get an error.

This is my app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  s = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  myHero = this.s[0];

}

interface Person {
  name: string;
  year: number; 
}

var people: Person[] = [{ name: 'robert', year: 1993 }];
var newPerson: Person = { name: 'joe', year: 1992 };

people.push(newPerson);

newPerson = {name: 'jose', year: 1997};

people.push(newPerson);


console.log(people[2].name);

This is my app.component.html file

<p>HEllo</p>


<ul>
  <li *ngFor="let name of s">
    {{ name }}
  </li>
</ul>


I want to do something to what I did in the html file but with the other array

Upvotes: 0

Views: 649

Answers (2)

Nicholas K
Nicholas K

Reputation: 15423

You need to place the statements within a method/constructor of a class which you are not doing, hence the compile time error. The ngOnInit() is the ideal place for your component to initialize its data.

Your component should look something like this:

export class AppComponent implements OnInit {
  people: Person[] = [];

  ngOnInit() {
    this.people  = [{ name: 'robert', year: 1993 }];
    let newPerson: Person = { name: 'joe', year: 1992 };
    this.people.push(newPerson);
    newPerson = {name: 'jose', year: 1997};
    this.people.push(newPerson);
    console.log(this.people[2].name);
  }
}

interface Person {
  name: string;
  year: number; 
}

And the template

<ul>
  <li *ngFor="let p of people">
    {{ p.name }}, {{ p.year }}
  </li>
</ul>

Here's a stackblitz for the same.

Upvotes: 1

caden311
caden311

Reputation: 981

You just need to treat the app component like a class. This shouldn't throw any errors.

import { Component } from '@angular/core';
interface Person {
  name: string;
  year: number;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  public s = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  public myHero = this.s[0];
  public people : Person[];
  public newPerson: Person;

  constructor() {
    this.people = [{ name: 'robert', year: 1993 }];
    this.newPerson = { name: 'joe', year: 1992 };

    this.people.push(newPerson);

    this.newPerson = {name: 'jose', year: 1997};

    this.people.push(newPerson);


    console.log(this.people[2].name);
  }

}

Upvotes: 3

Related Questions