所以我在这里有一个属性指令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');
}
}
答案 0 :(得分:9)
您可以像在组件
中一样使用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 :(得分:1)
如果你想将值传递给指令,那么你应该尝试这样:
这是我的自定义指令,我将从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中使用您的指令,并将数据发送到指令,如下面的代码所示。
我将name
和value
发送到test.directive.ts
。
<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div>
或
<div input-box [name]="componentObject.name" [value]="componentObject.value'"></div>
现在查看控制台或相应地使用指令中的数据。