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>を知っている限り、それは特に重大な問題ではありません。ElementCollectionNodeList

明らかに、属性にすべてを押し込んでコンテンツを空のままにするという回避策がありますが、それは醜いと思います (特に、閉じる必要のないタグを明らかに定義できないため)。

4

2 に答える 2

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>

afterContentInithtmlElは、スパンDOM 要素を参照します。その結果、次のようになります。

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

Angular 2.0.0-alpha.45に有効

ディレクティブまたは変数バインディングである子要素に関心がある場合、これは機能します。

'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
    }
}
于 2015-11-03T22:02:55.210 に答える