2017-01-06 42 views
1

由於某些原因,我無法弄清楚,我無法訪問對象的屬性,或者看起來如此。無法訪問Angular.io TypeScript組件中的屬性對象

@Component({ 
    selector: 'ab-table', 
    template:` 
    <h2>{{table.title}}</h2> 
    <table> 
    <thead> 
    <tr> 
    <th *ngFor="let head of table.headers"> 
    {{head}} 
    </th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr *ngFor="let row of table.rows"> 
    <td *ngFor="let item of row.items"> 
    {{item}} 
    </td> 
    </tr> 
    </tbody> 
    </table> 
    `/**/ 

此模板說EXCEPTION: Error in ./TableComponent class TableComponent - inline template:6:8 caused by: Cannot read property 'headers' of undefined

//template:`{{stringify(this.table.rows)}}`, 

而這一次也是如此,但如果我刪除.rows它給我,我期待JSON:

{ 
    "title":"myTest", 
    "headers":["test1","test2","test3"], 
    "rows":[ 
     { "items":["hi","there","now"] }, 
     { "items":["how","are","you"] } 
    ] 
} 

這裏是類聲明的其餘部分。

}) 
export class TableComponent { 
    @Input() table: Table; 
    stringify(item): string{ 
     return JSON.stringify(item); 
    } 
    getTable(key): any { 
     return this.table[key]; 
    } 
} 

如果有幫助的任何,這裏有表類定義。

export class Table { 
    title: string; 
    headers: string[]; 
    rows: TableRow[]; 
} 

export class TableRow{ 
    items: string[]; 
} 

回答

0

如果在異步方式得到table,包裝與*ngIf模板可能的幫助。

像這樣:

<div *ngIf="table"> 
    <h2>{{table.title}}</h2> 
     <table> 
     <thead> 
     <tr> 
     <th *ngFor="let head of table.headers"> 
     {{head}} 
     </th> 
     </tr> 
     </thead> 
     <tbody> 
     <tr *ngFor="let row of table.rows"> 
     <td *ngFor="let item of row.items"> 
     {{item}} 
     </td> 
     </tr> 
     </tbody> 
     </table> 
</div> 
+0

這做到了。我不認爲教程對此有任何說明。哦,對,教程使用一個數組,它可以是空的。 –

+0

@ArlenBeiler很高興你知道了:) – echonax