2017-04-15 10 views
1

ように私はここで、属性ディレクティブappGetCurrencyを持っている:角度2:属性ディレクティブからのパス値コンポーネント変数

<md-select appGetCurrency [(ngModel)]="value" placeholder="Currency" name="currency"> 
    <md-option *ngFor="let c of currencyList" [value]="c.code">{{c.dsc}}</md-option> 
</md-select> 

私はappGetCurrencyディレクティブが構築するためにcurrencyListにいくつかの値を渡すことを希望オプションのリスト

EDIT

appGetCurrencyディレクティブだけで、私は、ホストテンプレートにcurrencyList変数にそのリストを渡したい、サービスから通貨の一覧を取得する:

@Directive({ selector: '[appGetCurrency]' }) 

export class CurrencyDirective { 
    currencies; 

    constructor() { 
    // build the <md-options> based on 'currencies' 
    this.currencies = this.service.getCurrencies('asia'); 
    } 

} 
+0

この指令を表示できますか?それは何をするためのものか? – jonrsharpe

+0

@jonrsharpeが行った。何もそれに何もtho。ありがとう! – kyw

答えて

3

することができますコンポーネントと同じようにEventEmitterを使用してください。

@Directive({ selector: '[appGetCurrency]' }) 

export class CurrencyDirective { 
    @Output() onCurrencyEvent = new EventEmitter(); 
    currencies; 

    constructor() { 
    // build the <md-options> based on 'currencies' 
    this.currencies = this.service.getCurrencies('asia').subscribe((res)=>{ 
     this.onCurrencyEvent.emit(res); 
    }); 
    } 

} 

html:

<md-select appGetCurrency [(ngModel)]="value" placeholder="Currency" name="currency" (onCurrencyEvent)="currencyEventOnParent($event)"> 

親コンポーネント:

currencyEventOnParent(event){ 
    console.log(event); 
} 
+1

良い解決策と多くの時間を節約... – roshini

+0

@roshini喜んで私は助けることができる:-) – echonax

+0

もう一つの質問----ここで私は[(ngModel)]に選択値を取得することができません(私の場合は私はformControlNameを使用して)私はブートストラップの選択を使用しています。 – roshini

0

あなたはディレクティブに値を渡したいなら、あなたはこのように試してみてください:

これは私のカスタムディレクティブで、私は2つの値を共有するつもりですコンポーネントやHTMLから。

test.directive.ts:

import { Directive, ElementRef, Input, OnInit } from '@angular/core'; 

@Directive({ 
    selector: '[input-box]' 
}) 

export class TestDirectives implements OnInit { 
    @Input() name: string; 
    @Input() value: string; 
    constructor(private elementRef: ElementRef) { 
    } 
    ngOnInit() { 
     console.log("input-box keys : ", this.name, this.value); 
    } 
} 

、今、あなたのディレクティブが作成されていると、あなたのapp.module.ts以下のようにこのディレクティブを追加しています:

app.module.ts:

import { NgModule } from '@angular/core'; 
import { AppComponent } from './app.component'; 
import { TestDirectives } from '../directives/test.directive'; 


@NgModule({ 
    declarations: [ 
    AppComponent, 
    TestDirectives 
    ], 
    imports: [], 
    providers: [], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

あなたウィルあなたのhtmlであなたの指示を使用し、以下のコードのように指令にデータを送る必要があります。

namevaluetest.directive.tsに送信しています。

<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div> 

または

<div input-box [name]="componentObject.name" [value]="componentObject.value'"></div> 

今応じディレクティブでコンソールまたは使用データを参照してください。

関連する問題