【问题标题】:How to create an Angular directive to disable input fields如何创建 Angular 指令以禁用输入字段
【发布时间】:2021-11-12 22:36:18
【问题描述】:

我正在尝试创建一个指令以应用于输入和按钮,这将根据我从服务中获得的条件禁用元素。

我已经查看过,并尝试了以下方法:

  • Button @Directive to bind disable attribute via @Input in Angular
  • Angular2 attribute directive Hostbinding to host attribute
  • 我曾尝试将disabled 用于HostBinding,但我得到Can't bind to 'disabled' since it isn't a known property of 'button'.
  • 我曾尝试使用attr.disabled,但后来我得到Attempted to set attribute `disabled` on a container node. Host bindings are not valid on ng-container or ng-template.
  • 我确定我没有尝试绑定到 ng-container 或 ng-template,而是直接绑定到按钮或输入,如下例所示
  • 我可以使用[disabled]="condition" 直接绑定到禁用,但这不是我想要的

这是我目前对指令的看法:

export class InputPermissionsDirective {
  @Input() set appCanModify(name:string) {
    this.canModify(name);
  }
  @HostBinding('disabled') disabled:boolean = false;

  constructor(private permissionsService:PermissionsService) { }

  private canModify(name:string) {
    const routePermissions = this.permissionsService.getPermissionsByRoute(window.location.pathname);

    if(!routePermissions) this.disabled = true;
    else {
      const componentPermissions = this.permissionsService.getPermissionsByComponentName(routePermissions, name)

      if(componentPermissions && componentPermissions.CanModify) this.disabled = false;
      else this.disabled = true;
    }
  }

}

这里,权限服务查询与输入名称关联的权限级别(下例中的 FooBar)。从那里开始,应该根据元素的权限字段 CanModify 设置 disabled 属性。

这是我使用此指令的示例:

<input type="text" class="form-control" [(ngModel)]="foo" *appCanModify="'FooBar'">

我们将不胜感激,我可以根据需要提供更多信息。谢谢!

【问题讨论】:

  • 您应该能够直接绑定到按钮上的 [disabled] 属性。您确定在使用按钮的模块中导入了 CommonModule?
  • 是的,CommonModule 是通过我的应用程序通过共享模块导出导入的。正如您在输入字段和按钮上提到的那样,我仍然可以使用方括号绑定到禁用,但我需要通过此用例的指令来禁用。
  • 尝试将您的指令用作普通指令,而不是结构指令,因为您没有注入任何 ViewContainerRef 或 TemplateRef。所以directiveName 而不是*directiveName
  • 啊,我试试看。最初正在浏览包含星号的教程,但没有意识到其中的区别。我会试一试并阅读差异,谢谢!
  • @MikkelChristensen 成功了!非常感谢你的帮助。如果您想将该评论作为官方帖子提供,我会将其标记为答案。

标签: angular


【解决方案1】:

我的问题的解决方案是我试图通过使用星号将此指令用作结构指令。相反,我需要将其用作appCanModify

感谢@MikkelChristensen 的解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2014-02-11
    • 2018-10-17
    • 2022-11-16
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多