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

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

所以我在这里有一个属性指令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);
}

如果你想将值传递给指令,那么你应该这样尝试:

这是我的自定义指令,我将分享来自 componen 或 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 中使用您的指令并将数据发送到指令,如下面的代码所示。

我正在向 test.directive.ts 发送 namevalue

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

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

现在查看控制台或相应地在指令中使用数据。