所以在 Angular2 中,以下内容非常简单:
@Component({
selector: 'some',
properties: ['header']
})
@View({
template: `
<div>
<h2>{{ getFormattedHeader() }}</h2>
<p><content></content></p>
</div>
`
})
class SomeComponent {
header: string;
getFormattedHeader() {
return this.header + '!';
}
}
<some header="Header Text">Content</some>
你会得到这个:
<div>
<h2>Header Text!</h2>
<p>Content</p>
</div>
但是如果我想对内容应用格式怎么办?我可以写一个 getFormattedContent()
吗?函数,如果是,我用什么替换 this.header
与?
就此而言,我本可以选择使用 format(header)
在模板中,带有 format
接受一个字符串并返回带有 !
的字符串的方法.我可以在模板中放入类似于 format(
的任何内容吗? <content></content>
)
?显然是我的format
自<content></content>
以来,方法需要稍微复杂一些不是字符串,但只要我知道它的类型(ElementCollection
?NodeList
?),这就不是一个特别重要的问题。
显然,有一种解决方法,就是将所有内容都推到属性中并将内容留空,但我发现这很丑陋(特别是因为显然无法定义不需要关闭的标签)。
最佳答案
适用于 Angular 2.0.0-alpha.45
如果您对指令或变量绑定(bind)的子元素感兴趣,那么这将起作用:
从'angular2/angular2'导入{Component, Query QueryList};
@Component({
selector: 'c-item',
template: '<li><ng-content></ng-content></li>'
})
export class CItem {
}
@Component({
selector: 'c-container',
template: '<div><ul><ng-content></ng-content></ul><strong>{{children.length}} items found.</strong></div>',
directives: [CItem]
})
export class CContainer {
private children:QueryList<CItem>;
constructor(@Query(CItem) children:QueryList<CItem>) {
this.children = children;
}
afterContentInit() {
// now this.children variable is initialized properly
}
}
关于typescript - 类本身可以看到嵌入的内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31434309/