Angular 2通过绑定将html传递到ng-content [英] Angular 2 passing html to ng-content with bindings
问题描述
我正在为基础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
原始
ngTemplateOutlet
或ngForTemplate
可以用于该用例:
<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通过绑定将html传递到ng-content的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!