Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Pass value from attribute directive as a component variable

So I have a attribute directive appGetCurrency in here:

<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>

I would like that the appGetCurrency directive to pass some values to the currencyList in order to build the list of options.

EDIT

The appGetCurrency directive just get a list of currencies from a service, then I would like to pass that list to the currencyList variable in the host template:

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

export class CurrencyDirective {
  currencies;

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

}
like image 706
kyw Avatar asked Dec 11 '22 11:12

kyw


1 Answers

You can use an EventEmitter just like in a component

@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)">

Parent component:

currencyEventOnParent(event){
  console.log(event);
}
like image 78
eko Avatar answered Dec 13 '22 22:12

eko