* ngFor来自第二个对象的节目

时间:2017-08-05 15:23:21

标签: angular angular2-template

我无法找到我在测试角度2应用程序中具有的特定行为的原因

  1. 我已在我的App Component
  2. 中声明了Customers的列表
  3. 我在Customer参数@Input
  4. 中构建了一个名为Customer的子组件
  5. 在App html中,我通过* ngFor将客户对象传递给子组件,但在浏览器中我只能从第二个对象看到
  6. 这是我的应用程序组件

    const CUSTOMERS: Customer[] = [
    {Id: 1, name: "Adi"},
    {Id : 2, name: "Dan"},
    {Id : 3, name: "Yossi"},
    {Id : 4, name: "DavId"},
    {Id : 5, name: "Hadar"},
    {Id : 6, name: "Gil"},
    ];
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'This is my new app';
      Adi = "This is my name";
    
      customers = CUSTOMERS;
    
      ngOnInit (){
        console.log(this.customers);
      }
    }
    
    export class Customer {
      Id: number;
      name: string;
    }
    

    这是html

    <ul>
      <li *ngFor="let c of customers">
        <my-customer [customer]="c" ></my-customer>
      </li>
    </ul>
    

    这是子组件

    import {Customer} from '../app.component';
    
    
    @Component({
        selector: 'my-customer',
        templateUrl: './Customer.Component.html',
    })
    export class CustomerComponent implements OnInit {
        @Input() customer: Customer;
        constructor() {
    
         }
    
        ngOnInit() { 
    
        }
    }
    

    我只能从第二个对象看到的任何理由? 意思是我没有看到'Adi'对象

1 个答案:

答案 0 :(得分:0)

很奇怪。您可以检查控制台并检查是否呈现所有元素。

我检查了你的代码并创建了我的样本,一切都适合我,我的意思是我能够看到来自客户对象的所有数据。

检查根据您的要求创建的这个plunker演示。

https://plnkr.co/edit/sFR5Uv?p=preview

**app.ts**

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {CustomerComponent} from './child.component'
const CUSTOMERS: Customer[] = [
{Id: 1, name: "Adi"},
{Id : 2, name: "Dan"},
{Id : 3, name: "Yossi"},
{Id : 4, name: "DavId"},
{Id : 5, name: "Hadar"},
{Id : 6, name: "Gil"},
];
export class Customer {
  Id: number;
  name: string;
}
@Component({
  selector: 'my-app',
  template: `
    <ul>
  <li *ngFor="let c of customers">
    <my-customer [customer]="c" ></my-customer>
  </li>
</ul>
  `,
})
export class App {

   title = 'This is my new app';
  Adi = "This is my name";

  customers = CUSTOMERS;



  constructor() {

  }

}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, CustomerComponent ],
  bootstrap: [ App ]
})
export class AppModule {}



**child.component**


import {Customer} from './app';
import {Component, Input} from '@angular/core'

@Component({
    selector: 'my-customer',
    template: '<div>{{customer.name}}</div>',
})
export class CustomerComponent implements OnInit {
    @Input() customer: Customer;
    constructor() {

     }

    ngOnInit() { 

    }
}