2

到目前为止,我还没有找到任何代码片段,而且文档太简洁了。所以我的问题是如何将参数传递给 ng-template 以及如何取回索引?直观地说,以下应该可以工作,但它只是抛出“未定义”。任何帮助表示赞赏。

@ViewChild("vc", { read: ViewContainerRef }) vc: ViewContainerRef;
  @ViewChild("tpl") tpl: TemplateRef<any>;

  ngAfterViewInit() {
    this.vc.createEmbeddedView(this.tpl,
      new Book("The Complete Guide to Angular 4", 55));
    this.vc.createEmbeddedView(this.tpl,
      new Book("Building Web Components with TypeScript and Angular 4", 48));
  }
  deleteBook(index) {
    console.log("deleteBook index ", index);
  }

<div class="container">
    <div class="card-deck">
        <ng-container #vc></ng-container>
    </div>
    <ng-template #tpl let-book="book" let-index="index">
        <div class="card">
            <img class="card-img-top" src="..." alt="Card image cap">
            <div class="card-block">
                <h4 class="card-title">Title: {{book.title}}</h4>
                <p class="card-text">Price: {{book.price}}</p>
                <button type="button" class="btn btn-primary" (click)="deleteBook(index)">Delete</button>

            </div>
        </div>
    </ng-template>
</div>
4

1 回答 1

6

let-keyname您需要使用与语法匹配的键传递一个对象:

<ng-template #tpl let-book="book" let-index="index">
   ...

this.vc.createEmbeddedView(this.tpl, { 
    book: new Book("The Complete Guide to Angular 4", 55), 
    index: someIndex 
});
于 2017-08-03T04:54:39.143 回答