2016-11-22 62 views
6

我開始使用Angular2(最終版本),我遇到了一些問題* ngFor。Angular2(final version)* ngFor在組件中:由於它不是'div'的已知屬性,因此無法綁定到'ngForOf'

我已經建立了以下組件樹: 主 - >儀表板 - >提醒

Unhandled Promise rejection: Template parse errors: Can't bind to 'ngForOf' since it isn't a known property of 'div'.

("<div class="item" [ERROR ->] *ngFor="let alert of alerts"> "): [email protected]:20 Property binding ngForOf not used by any directive on an embedded template.

Make sure that the property name is spelled correctly and all directives are listed in the "directives" section.

它工作正常,但,當我嘗試添加* ngFor在警報組成部分循環,我得到了以下錯誤:

DashboardAlertsComponent

import {Component, OnInit} from "@angular/core"; 
import {Alert} from "../../shared/models/alert.model"; 

@Component({ 
    selector: 'dashboard-alerts', 
    templateUrl: './alerts.component.html' 
}) 
export class DashboardAlertsComponent implements OnInit { 

    alerts:Alert[] = new Array<Alert>(); 
    constructor() { 
    this.alerts.push(new Alert('1', 'high', 'My alert1', '12/11/2016 4:50 PM')); 
    this.alerts.push(new Alert('2', 'low', 'My alert2', '11/11/2016 9:50 PM')); 
    this.alerts.push(new Alert('3', 'medium', 'My alert3', '10/11/2016 2:50 PM')); 
    } 

    ngOnInit() { 
    } 
} 

警報.component.html

<div class="item" *ngFor="let alert of alerts"> 
    <span class="priority {{ alert }}"></span> 
    <span class="title">{{ alert }}</span> 
    <span class="time">3:40 PM</span> 
    <a href="#" class="more-actions"><span>Actions</span></a> 
</div> 

DashboardModule

@NgModule({ 
    declarations: [ 
    DashboardAlertsComponent 
    ], 
    providers: [], 
    directives: [], 
}) 
export class DashboardModule { 
} 

的AppModule

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

P.S我讀了這個問題很多建議的解決方案,但沒有人解決了這個

+0

http://stackoverflow.com/questions/34228971/cant-bind-to-ng-forof-since-it-isnt-a-known-native-property/ 34229918#34229918 –

回答

9

您應該在主模塊中導入CommonModule,並在其他模塊中導入BrowserModule(如果您正在使用多個模塊)。我得到了同樣的問題,它對我來說工作正常

+0

你確定嗎?我做了相反的事情(主模塊中的BrowserModule和子模塊中的CommonModule),它的工作原理是什麼? –

+0

看看這裏:https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-browser-vs-common-module –

+0

是的你是對的,我交換了他們。但我認爲這是問題的根源:) –

相關問題