Angular 2: How to access Template Input Variables

2019-09-13 15:43发布

问题:

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.

回答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>


回答2:

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>


标签: angular