How to pass values to directive in angular

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)