2017-08-10 58 views
0

我正在寻找动态地将一些数据加载到表中。数据将显示在页面上,但它不会在我的HTML表格中正确格式化。所有文本都出现在一行中,并且没有任何表格格式。我有以下信息的自定义组件:Angular 2 - 组件无法正确呈现表标记

HTML

<table class="table table-hover"> 
    <thead> 
     <tr> 
     <th>Book Name</th> 
     <th>Author Name</th> 
     </tr> 
    </thead> 
    <tbody> 
     <app-books *ngFor="let book of booksArray" [book]="book"></app-books> 
    </tbody> 
    </table> 

我有叫app-books子组件的@input()装饰。

应用书籍打字稿文件

@Input() book: {title: string, author: string, cover_img: string}; 

    constructor() { 
    } 

应用书籍的HTML文件

<tr> 
    <td>{{ book.title }}</td> 
    <td>{{ book.author }}</td> 
</tr> 

回答

2

如果你看看你的标记,你会看到的您的tr嵌入在app-books标记中。所以你的标记是无效的。见

enter image description here

要解决这个问题,我建议你使用[app-book]为您的组件,以便您可以将其指定为tr元素的属性:

<tr *ngFor="let book of booksArray" [app-book]="book"></tr> 

此外,从去除<tr></tr>您的app-book组件标记。请参阅说明这一点的Plunker sample

编辑

角4引入了NgComponentOutlet指令,可能是在这种情况下非常有用。但是,它不允许将Input参数传递给引用的组件。请参阅There is no way to access inputs or outputs of Components created by NgComponentOutlet问题。但是,我发现​​包可以做到这一点。所以,你的代码可能是:

父组件:

<table class="table table-hover"> 
    <thead> 
     <tr> 
      <th>Book Name</th> 
      <th>Author Name</th> 
     </tr> 
    </thead> 
    <tbody> 
     <ng-template ngFor let-item [ngForOf]="booksArray" let-i="index" [ngForTrackBy]="trackByFn"> 
      <ng-container [ngComponentOutlet]="AppBook" [ndcDynamicInputs]="{book: item}"></ng-container> 
     </ng-template> 
    </tbody> 
</table> 

行组件:

@Component({ 
    selector: 'tr[app-book]', 
    template: ` 
    <td>{{ book?.title }}</td> 
    <td>{{ book?.author }}</td> 
    ` 
}) 
export class AppBook { 
    @Input() book: { title: string, author: string, cover_img: string }; 
} 

tr[app-book]选择是很重要的位置。它告诉Angular使用app-book属性呈现tr元素。如果您将其指定为app-book,则Angular将呈现<app-book>标记,这是无效的标记。如果您将其指定为[app-book],则Angular将渲染<div app-book>,这也是无效的。请参阅说明这一点的sample

+0

酷!我原以为我们不能将表的任何部分分隔成一个子组件。所以你*不能*从'table'或'tbody'中分离'tr',但是你可以把'td'和'tr'分开。很高兴知道!谢谢! – DeborahK

+0

这是我一起去的路线。谢谢(你的)信息! –

+1

@RyanShocker我非常喜欢这种情况,我花了一些时间来寻找更好的解决方案。查看更新后的答案。 –

1

如果您通过完整的booksArray到子组件,它不仅使它成为关注较好的分离,但它也允许您在组件级别操作数据。

试试这个:

App.html

<app-books [books]="booksArray"></app-books> 

AppBooksComponent.ts

export default class AppBooksComponent { 
    @Input('booksArray') books: any; 
    constructor() {} 
} 

AppBooksComponent.html

<tr *ngFor="book in books"> 
    <td>{{ book.title }}</td> 
    <td>{{ book.author }}</td> 
</tr> 
+0

看起来不错,谢谢! –

+0

奇怪的是,HTML表格中的格式仍然稍微偏离。 –