2017-04-15 122 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選項列表。

編輯

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完成。沒什麼太多。謝謝! – 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

如果你想傳遞的價值指示,你應該嘗試這樣的:

這是我的自定義指令,並且我要共享兩個值從組件或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> 

現在看到相應的指令控制檯或使用的數據。