My code,
My model component,
@Component({
sele
Use @input and pass value from parent component, where this component was used like [imgval]="val"
If you want to send data to directive then you should try like this:
This is my custom directive, and I am going to share two value from component or HTML to the directive.
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.
This is an Example how you can pass value to a Directive
Directive
import {Directive, Input, HostListener} from '@angular/core';
@Directive({
selector: '[appConfirm]'
})
export class ConfirmDirective {
//we can also add the attribute directive liek this [appconfirm] if the input in the directive has same name as appConfirm like
//@Input() appConfirm:string; and then in component button we can use the directive like
//<button type="button" [appConfirm] = "Rahul">Click to Send to Directive</button>
@Input() value:string;
@HostListener('click',['$event'])
confirm(){
const confirmed = window.confirm("Are you Sure ?");
if(confirmed){
window.alert("This is Value ["+this.value+"] Passed by the Component to the Directive")
}
}
constructor() { }
}
ComponentTemplate.html
<button type="button" appConfirm value = "Rahul">Click to Send to Directive</button>
For more info look this repo https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/directives