0

角度2 rc 1、TypeScriptで書かれています。ディレクティブまたはコンポーネントを属性ディレクティブに挿入するにはどうすればよいですか?

私はセレクタmyDirectiveと属性ディレクティブを持っています。その目的は、頻繁に再利用するhtmlの部分を構築することです。その作業を行うために、一致するクラスはカスタムコンポーネントと別の属性ディレクティブにアクセスする必要があります。私はmyDirectiveのクラス内に属性ディレクティブまたはコンポーネントを挿入する方法を考え出すのに問題があります。

@Directive({selector: '[myDirective]'}) 
export class MyDirective{ 
    constructor(private renderer:Renderer, private elementRef:ElementRef) { 
     let el = elementRef.nativeElement; //capture the HTML element host 
     let innerElement = renderer.createElement(el,'my-component',null); 
     renderer.setElementAttribute(innerElement,'myOtherDirective',''); 
    } 
} 

使用法:<div myDirective></div>

生成されたHTML:<div><my-component myOtherDirective=''></my-component></div>

問題がmy-componentmyOtherDirectiveが角テンプレートパーサによって処理されていない、そしてもちろん、ブラウザがそれらを認識しないということです。

  1. 属性ディレクティブに別のディレクティブまたはコンポーネントを挿入するにはどうすればよいですか。

  2. ここで属性デ​​ィレクティブを誤って使用していますか?コンポーネントはより適していますか?

答えて

3

これは、あなたが

<my-component></my-component> 

Basicの例のようにそれを使用することができますので、代わりにComponentを作成Directive の誤用である:http://learnangular2.com/components/

アップデート:ここでは一例で

@Component({ 
    selector: 'parent-component', 
    template: ` 
    <div> I'm a parent component!!! 
     <child-component></child-component> 
    </div> 
    `, 
    directive: [ChildComponent] 
}) 

@Component({ 
    selector: 'child-component', 
    template: ` 
    <div> I'm a child component!!! 
    </div> 
    ` 
}) 
  • メンバー注釈Component参照ChildComponentdirective、すなわちChildComponentからものを使用するようにParentComponentに指示します。
  • AngularはChildComponentのselector: 'child-component'を見て、ParentComponentテンプレートにchild-componentタグがあるテンプレートを挿入します。

注釈Componentのメンバーdirectiveは少し誤解を招くことがあります。あなただけDirectiveはここに参照することができると思うかもしれないが、それは属性DirectiveについてComponents

を参照するためにも場所です:

@Component({ 
    selector: 'my-component', 
    template: ` 
    <div my-directive> I'm a component with directive!!! 
    </div> 
    `, 
    directive: [MyDirective] 
}) 

@Directive({ 
    selector: '[my-directive]' 
}) 

あなたは属性ディレクティブ

<div [my-directive]="I'm a value!"> I'm a component with directive!!!</div> 

を使用して値を渡すことができます詳細については、公式ドキュメントをチェックしてください:私は見てあなたをお勧めしますhttps://angular.io/docs/ts/latest/guide/attribute-directives.html

このビデオレッスンhttps://youtu.be/_-CD_5YhJTA。それは私にとって非常に有益でした。

+1

私は応答を待っている間に同じ結論に達し、コンポーネントを構築しました。私は、コンポーネントが適切であるときと属性指示があるときとの間の明確な境界を見つけるのが少し難しいと思う。私は、ビューテンプレートが必要な場合は、コンポーネントを使用する必要があるということが、私が思いつくことができる最高のものだと思います。提案のための親指;私はまだ別のディレクティブに属性ディレクティブを挿入する方法を知ります。 – BeetleJuice

+0

それはまさに違いです。コンポーネントにはビューがあり、ディレクティブにはありません。 –

関連する問題