0

How do I access Template Input Variables in my own Custom Structural Directive?

@Directive({
   selector: "[myCustomDirective]"
})
export class MyCustomDirective {
}

The documentation says that A template input variable is a variable whose value you can reference within a single instance of the template.

<div *myCustomDirective="let visible = true"></div>

I know that the template now has an input called let-visible but how do I access it?

------------------- EDIT -------------------

I want to be able to accept multiple Inputs using the structural directive. Is that possible?

I want one Input to be assigned to myCustomDirective itself and one to visible thats why I was trying to use the let visible syntax like ngFor does.

Bengi Besçeli
  • 3,638
  • 12
  • 53
  • 87
takeradi
  • 3,661
  • 7
  • 29
  • 53

2 Answers2

1

You have to also import Input at the top of your directive module.

@Directive({
   selector: "[myCustomDirective]"
})
export class MyCustomDirective {
  @Input()
  set myCustomDirective(isVisible: boolean): void {
    // do something with isVisible
  }
}

Usage of directive.

<div *myCustomDirective="true"></div>
Igor
  • 60,821
  • 10
  • 100
  • 175
  • But I did mention that I am creating my own custom Structural Directive. Thats why it leads with the `*` character. – takeradi Mar 01 '17 at 16:37
  • @takeradi - I removed the comment but I will leave the rest as is considering its applicable to either type of directive. – Igor Mar 01 '17 at 16:38
  • So your answer is not valid for my case. Also I am not sure if you can use a `[visible]` input on a `div`. Div is not a custom component so how can you assign an `Input` to it? – takeradi Mar 01 '17 at 16:39
0

You can try the below:

            import { Directive,Input,...} from '@angular/core';
            @Directive({
               selector: "[myCustomDirective]"
            })
            export class MyCustomDirective {

            //using the Input decorator, we can accept the value of the property (in our case, it is myCustomDirective)and //use it inside our directive class.
             @Input('myCustomDirective')
              private visible: boolean;

              //console.log(this.visible);

            }

            // Use it, maybe like this:
            <div *myCustomDirective="true"></div>
user6801750
  • 242
  • 3
  • 12