简体   繁体   中英

How to create an Angular directive to disable input fields

I am trying to create a directive to be applied to inputs and buttons, that will disable the element based on a condition that I get from a service.

I have already reviewed, and tried the following:

  • Button @Directive to bind disable attribute via @Input in Angular
  • Angular2 attribute directive Hostbinding to host attribute
  • I have tried using just disabled for the HostBinding, but I get Can't bind to 'disabled' since it isn't a known property of 'button'.
  • I have tried using attr.disabled , but then I get Attempted to set attribute `disabled` on a container node. Host bindings are not valid on ng-container or ng-template. Attempted to set attribute `disabled` on a container node. Host bindings are not valid on ng-container or ng-template.
  • I am sure that I am not trying to bind to ng-container or ng-template, I am binding directly to a button or input as in the example below
  • I am able to bind directly to disabled using [disabled]="condition" , but that is not what I want here

Here is what I currently have for the directive:

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;
    }
  }

}

Here, the permissions service queries for the permission levels associated with the input name (FooBar in the below example). From there, the disabled attribute should be set according to the element's permission field CanModify.

And here is an example of me using this directive:

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

Any help here would be greatly appreciated, and I can provide additional info as needed. Thanks!

The solution to my issue was that I was trying to use this directive as a structural directive by using the asterisk. Instead, I needed to use it as appCanModify

Thanks to @MikkelChristensen for the solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM