Angular 4不显示数据 - 简单示例不起作用

时间:2018-02-23 22:02:02

标签: angular typescript

我试图显示一些数据,但Angular只显示空的子弹点。我收到错误,上面写着“无法读取0 undefined的属性”。代码对我来说似乎没问题但是没有用。怎么了?

我的代码是:

a)Offer.ts

export class Offer
{
    constructor(
      public id      : number,
      public title   : string,
      public owner   : string,
      public productOffer    : [ {'id': number, 'name': string} ]) {}
}

b)offer.component.ts

<!-- language: lang-js -->
import { Component, OnInit } from '@angular/core';
import { Offer } from '/offer';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser"; 

 @Component({
  selector   : 'app-offers',
  templateUrl: './offers.html',
  styleUrls  : ['./offers.scss']
            })  

export class OffersComponent implements OnInit {
 public offers: Offer[];
  constructor() { 
    this.offers = [
      {
        id : 1,
        title : 'Offer 01',
        owner : 'Mr Owner',
        productOffer : [                                                 
           { id : 1, name: 'Soap'},
           { id : 2, name: 'Cover'},
                  ]
      },
      {
        id : 2,
        title : 'Offer 01',
        owner : 'Mr Owner2',
        productOffer : [                                                 
           { id : 1, name: 'Soap2'},
           { id : 2, name: 'Cover2'},
                  ]
              }];               
          }

         ngOnInit() {  } 

        }

c)offer.component.html

<ul ng-repeat="offer in offers">
        <li>example</li>
        <li><h1>{{ offer.owner }}</h1></li>
        <li>{{offer.title}}</li><br><br>
        <li><button>{{offer.id}}</button></li>
</ul>

d)我也尝试过:

  <ul>
    <li>example</li>
    <li *ngFor="let offer of offers">{{ offer.owner }}</li>     
  </ul>

我得到的输出是:

enter image description here

这个错误:

enter image description here

感谢您的帮助。我已经花了好几个小时试图解决它,但我不明白为什么不工作。

1 个答案:

答案 0 :(得分:0)

您将AngularJS与Angular混合使用(从版本2开始,现在它是版本5.2): 每种语法都是:

<!-- AngularJS -->
<ul>
  <li ng-repeat="item in items">
    {{$index}} {{item}}
  </li>
</ul> 

<!-- Angular -->
<ul>
  <li *ngFor="let item of items; let i = index">
    {{i}} {{item}}
  </li>
</ul>