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');
}
}
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);
}
If you want to pass value to directive then you should try like this:
This is my custom directive, and I am going to share two value from componen or 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);
}
}
and now your directive has been created and you will have add this directive into your app.module.ts like below:
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 { }
You will have to use your directive in your html and send data to the directive like in below code.
I am sending name and value to the test.directive.ts .
<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div>
or
<div input-box [name]="componentObject.name" [value]="componentObject.value'"></div>
Now see the console or use data in the directive accordingly.