How to pass values to directive in angular

Tracker picture Tracker · Mar 30, 2017 · Viewed 41.9k times · Source

My code,

  <modal *ngIf='showModal' [imageValue]="imageId"></modal>

My model component,

@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})


export class ModalComponent  {
  imageValue:any;

I want to get the value of this 'imageValue' but I dont know how to do it.Can anyone please help me.Thanks.

Answer

Shubham Verma picture Shubham Verma · Aug 10, 2017

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.