Angular 2通过绑定将html传递到ng-content [英] Angular 2 passing html to ng-content with bindings

查看:111
本文介绍了Angular 2通过绑定将html传递到ng-content的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为基础CSS框架编写角度组件.我正在使用tabs组件,并且希望能够将一些HTML传递给它的<ng-content>.

I'm writing angular components for the foundation css framework. I am working on the tabs component, and want to be able to pass some HTML to the <ng-content> of this.

问题是,我还需要传递html,用户可以将其放在上面,如下所示:

The problem is, I also need to pass html which a user can put bindings on, like this:

父模板

<tabs [data]='example'>
    <div> Age <br> {{item.age}} </div>`
</tabs>

TABS组件

<ul class="tabs" #tabs>
  <li *ngFor="let item of data | async" (click)="tabClick($event)">
      <a>{{item.name}}</a>
  </li>
</ul>
<div>
  <ng-content></ng-content>
</div>

TABS TYPESCRIPT

@Component({
  selector: 'tabs',
  templateUrl: './tabs.component.html'
})

export class TabsComponent {
  @Input('data') data:any;
  @ViewChild('tabs') tabs: ElementRef;
}

item是对example数组中对象的引用.

Where item is a reference to an object in the example array.

但是,出现此错误: Cannot read property 'name' of undefined 在将item插入<ng-content>指令之前对其进行评估.

However, I get this error: Cannot read property 'name' of undefined as item is being evaluated before it is inserted into the <ng-content> directive.

有没有办法解决这个限制,还是我走错路了?

Is there a way to get around this limitation, or am I going about this the wrong way?

推荐答案

更新Angular 5

ngOutletContext重命名为ngTemplateOutletContext

另请参见 https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

原始

ngTemplateOutletngForTemplate可以用于该用例:

<tabs [data]='example'>
  <ng-template let-item>
    <div> Age <br> {{item.age}} </div>`
  </ng-template>
</tabs>

@Component({
  ...
  template: `
    <ul class="tabs" #tabs>
      <li *ngFor="let item of data | async" (click)="tabClick($event)">
          <a>{{item.name}}</a>
      </li>
    </ul>
    <div>
      <ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: (data | async)}"></ng-template>
    </div>
  `
})
class TabsComponent {
  @ContentChild(TemplateRef) templateRef:TemplateRef;
}

另请参见 Angular 2将已包含的内容绑定到循环变量

这篇关于Angular 2通过绑定将html传递到ng-content的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆