【问题标题】:Is it possible to create a dynamic directive selector (like [class.active])?是否可以创建动态指令选择器(如 [class.active])?
【发布时间】:2021-03-11 14:44:00
【问题描述】:

我想创建一个带有半动态选择器的指令。

Angular 团队在某些地方使用这种方法,例如 [style.width.px]="100"(keyup.enter)="doSomething()"

在我的自定义指令中有一种方法可以做到这一点吗?类似于[my-directive.some-data]="variable"

【问题讨论】:

    标签: angular typescript angular-directive


    【解决方案1】:

    您可以在指令中添加@Input(),尽管语法与您编写的略有不同。

    所以你可以做类似的事情

    <p myDirective [someData]="variable">lorem ipsum</p>
    

    查看the angular docs了解更多信息

    编辑: 如果您想查看具有多个输入的示例,请查看this answer here

    【讨论】:

      【解决方案2】:

      发布答案后,我认为这确实不是您要寻找的,但是....您可以创建如下指令:

      @Directive({
        selector: '[mydirective.one],[mydirective.two],[mydirective.three]'
      })
      export class MyDirective implements OnInit {
        @Input('mydirective.one') prop1
        @Input('mydirective.two') prop2
        @Input('mydirective.three') prop3
      
        constructor(private el:ElementRef,private renderer:Renderer2) {}
         ngOnInit()
         {
          console.log(this.prop1,this.prop2,this.prop3)
          if (this.prop1)
             this.renderer.setStyle(this.el.nativeElement,"background-color",prop1)
      
          if (this.prop2)
             this.renderer.setStyle(this.el.nativeElement,"color",prop2)
      
          if (this.prop3)
             this.renderer.setStyle(this.el.nativeElement,"font-size",prop3)
      
         }
      }
      

      看看如何用逗号分隔选择器,你需要使用@Input(name.prop) variable的方式,因为你不能使用点分隔的变量

      更新 perfahs 您正在寻找主机。你可以声明一个类似的指令

      @Directive({
        selector: '[mydirective]',
        host:{'[class.active]':'value'}
      })
      export class MyDirective {
        value:boolean=false;
        @Input() set mydirective(value)
        {
            this.value=value;
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-06
        • 2020-12-26
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多