[Fixed] attribute binding and ng directive cause unrendered webpage

Issue

I am learning Angular and I follow the directions and guidance stated in the following tutorial.

The problem I am facing is, that when I run

ng serve --open

I do not see the items displayed on the page on the http://localhost:4200/, but I got the page shown in the screenshot below instead.

I expect to see the items displayed as the code posted below implies.

Please let me know where my mistake is and how to fix it so I can see the list of items displayed on the webpage.

app.component.ts:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class item {
  code: number;
  name: string;

  constructor(code: number, name: string) {
    this.code = code;
    this.name = name;
  }

   items = [
    new item(1, 'Mobile'),
    new item(1, 'Laptop'),
    new item(1, 'Desktop'),
    new item(1, 'Printer')
  ]
}

app.component.html:

<p>item</p>
<ul>
  <li *ngFor = "let d of items">
    <p>{{d.code}}</p>
    <p>{{d.name}}</p>
  </li>
</ul>

image:

enter image description here

Solution

You should do like this.

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

export class item {
  code: number;
  name: string;

  constructor(code: number, name: string) {
    this.code = code;
    this.name = name;
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  items = [
    new item(1, 'Mobile'),
    new item(1, 'Laptop'),
    new item(1, 'Desktop'),
    new item(1, 'Printer')
  ]

  constructor() {}
}

Leave a Reply

(*) Required, Your email will not be published