【问题标题】:Angular 2: How to access Template Input Variables in Structural DirectivesAngular 2:如何在结构指令中访问模板输入变量
【发布时间】:2017-07-21 02:00:14
【问题描述】:

如何在我自己的自定义结构指令中访问Template Input Variables

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

文档说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>

我知道模板现在有一个名为 let-visible 的输入,但我如何访问它?

------------------- 编辑 -------------------

我希望能够使用结构指令接受多个输入。这可能吗?

我希望将一个输入分配给myCustomDirective 本身,一个分配给visible,这就是我尝试使用let visible 语法的原因,就像ngFor 一样。

【问题讨论】:

  • 您想访问自定义结构指令中“可见”的值吗?
  • 是的。这可能吗?

标签: angular


【解决方案1】:

您还必须在指令模块的顶部导入 Input

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

指令的使用。

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

【讨论】:

  • 但我确实提到我正在创建自己的自定义结构指令。这就是为什么它以* 字符开头。
  • @takeradi - 我删除了评论,但考虑到它适用于任一类型的指令,我将保留其余部分。
  • 所以你的回答对我的情况无效。另外我不确定您是否可以在div 上使用[visible] 输入。 Div 不是自定义组件,那么如何为它分配Input
【解决方案2】:

您可以尝试以下方法:

            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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 2016-11-11
    • 2017-04-28
    • 2021-07-10
    • 2017-05-14
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多