Angular 2:将属性指令的值传递为组件变量

前端之家收集整理的这篇文章主要介绍了Angular 2:将属性指令的值传递为组件变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我在这里有一个属性指令appGetCurrency:

<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'); 
  }

}

解决方法

您可以像在组件中一样使用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);
}

猜你在找的Angularjs相关文章