takeradi
takeradi

Reputation: 3861

Angular 2: How to access Template Input Variables in Structural Directives

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.

Upvotes: 0

Views: 1169

Answers (2)

user6801750
user6801750

Reputation: 242

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>

Upvotes: 0

Igor
Igor

Reputation: 62228

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>

Upvotes: 1

Related Questions