typescript - 类本身可以看到嵌入的内容吗?

标签 typescript angular transclusion

所以在 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>以来,方法需要稍微复杂一些不是字符串,但只要我知道它的类型(ElementCollectionNodeList?),这就不是一个特别重要的问题。

显然,有一种解决方法,就是将所有内容都推到属性中并将内容留空,但我发现这很丑陋(特别是因为显然无法定义不需要关闭的标签)。

最佳答案

适用于 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/

相关文章:

javascript - 给定数组 "distribute/scale"的数量到特定值

angularjs - 如何在 typescript 中使用 angularjs app.service 和 $q

performance - 我们应该使用 _.foreach() 还是更好地使用 TypeScript 中的原生 for of 循环

Angular - 只允许 ng-content 中的文本

reactjs - 类型检查无状态组件中的 styled-components Prop

angular - 类型 'By' 与类型 'Locator' 没有共同的属性

Angular 2 CLI 这么多时间编译

Angular 6 更新 Observable

AngularJS:如何转换和替换包含元素