2016-04-02 13 views
1

私はカスタムディレクティブ<foo checked></foo>を持っています。 fooのテンプレートには<input type="checkbox">があります。 checkedfooにある場合は、<input type="checkbox" checked>が必要です。私は値を持たないこれらの属性を処理し、検出し、子要素が存在する場合にそれらにマークする方法をまだ見ていません。角2 - "checked"属性をテンプレートの子に渡すには?

これは役に立ちます。

答えて

7

次のことを試してみてください。ここで

も同様plunkerです:https://plnkr.co/edit/1JTijgHGvIGYMpDYC2i8?p=preview

import {Component,Attribute} from 'angular2/core' 

@Component({ 
    selector: 'child', 
    providers: [], 
    template: ` 
    <div> 
     <input type="checkbox" [checked]="isChecked"> 
    </div> 
    `, 
    directives: [] 
}) 
export class Child { 
    isChecked; 
    constructor(@Attribute("checked") checked) { 
    this.isChecked = !(checked === null); 
    } 
} 

@Component({ 
    selector: 'my-app', 
    providers: [], 
    template: ` 
    <div> 
     <child checked></child> 
     <child></child> 
    </div> 
    `, 
    directives: [Child] 
}) 
export class App { 
} 
2

私はあなたのディレクティブのコンストラクタであなたが持つことができ、あなたの要件ごとに考えて: -

フー・ディレクティブ -

import {Directive, Attribute} from 'angular2/core'; 
@Directive({ 
    selector: 'foo' 
}) 
export class foo { 
    constructor(@Attribute('checked') checked: string) { 
      if (checked === null){ 
       //checked is not present 
      }else{ 
       //checked is present 
      } 
... 
    } 
.... 
} 

とすることができます。 -

<foo checked></foo> 
関連する問題