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.

2
  • You want to access the value of "visible" inside your custom structural directive? Commented Mar 1, 2017 at 16:31
  • Yes. Is that possible? Commented Mar 1, 2017 at 16:33

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

But I did mention that I am creating my own custom Structural Directive. Thats why it leads with the * character.
@takeradi - I removed the comment but I will leave the rest as is considering its applicable to either type of directive.
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?
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.