2

因此,在 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),这并不是一个特别重要的问题。

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

4

2 回答 2

0

Valid for Angular 2.0.0-alpha.45

If you are interested in child elements, that are directives or variable bindings, then this will work:

import {Component, Query QueryList} from 'angular2/angular2';

@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
    }
}
于 2015-11-03T22:02:55.210 回答
0

适用于Angular 2.0.0-alpha.45

您可以考虑一个允许您访问 HTMLElement 及其子元素的指令。考虑一个例子:

import {Directive, CORE_DIRECTIVES, ElementRef, HTMLElement} from 'angular2/angular2';


@Directive({
    selector: '[my-border]',
    inputs: [
    'definition : my-border' // attribute my-border to var definition
    ]
})
export class MyBorder {
    private definition:string;
    private elementRef : ElementRef;

    constructor(elementRef : ElementRef) {
        this.elementRef = elementRef;
    }

    afterContentInit() {
        // now this.children variable is initialized properly
        let htmlEl:HTMLElement = this.elementRef.nativeElement;
        htmlEl.setAttribute('style', 'border:' + this.definition);
    }

然后你可以按如下方式使用它:

<span my-border="dashed #00b3ee thin;">This has directive my-border</span>

afterContentInit中的htmlEl指的是span DOM 元素。结果你得到:

<span my-border="dashed #00b3ee thin;" style="border:dashed #00b3ee thin;">This has directive my-border</span>
于 2015-11-04T15:43:15.047 回答