首页 > 解决方案 > Angular:未在指令中获取表单原始/无效状态的引用

问题描述

我有一个在组件内部使用的指令“hasPermission”。该指令的功能是检查权限,如果没有则禁用按钮,但是当我对表单字段进行任何更改(例如添加一些文本)时,它会再次启用按钮,这是由于 [disabled] 属性正在寻找原始表单/无效状态。

我该如何管理?

我想首先检查权限是否存在,然后只有这个原始/无效进入图片。请指导。

如果我得到这个表单的原始/无效内部指令的状态,我相信我们可以管理它,但是如何把它放进去,我尝试了一些使用 DoCheck/Host 等的解决方案,没有给我指令中的表单参考。

我不想使用 nativeElement (直到有人说这是唯一的方法:))

在此处输入图像描述

示例代码

   import {
    Directive,
    OnInit
} from '@angular/core';
import {
    NgForm
} from '@angular/forms';
@Directive({
    selector: '[haspermission]'
})
export class HaspermissionDirective implements OnInit {
    constructor() {
        ....
    }
    ngOnInit() {
        this.someService.getCurrentUser().subscribe(response => {
            this.store(response);
        });

    }

    store(data: IUser) {
        this.roles = JSON.parse(data.role);
        //.....doing some logic to calculate permissisons
        var hasPerm = this.roles.find(o => (o.RoleCode in permConfig.permission));
        if (!hasPerm) {
            this.element.nativeElement.disabled = true;
        }
    }
}

标签: angularangular-directive

解决方案


使用可以在指令装饰器上使用 exportAs 属性。这将暴露 appHaspermission 指令实例。

exportAs 采用在模板中导出组件实例的名称。

appHaspermission.Directive.ts

import { Directive, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
@Directive({
  selector: '[appHaspermission]',
  exportAs: 'hasPermission'
})
export class HaspermissionDirective implements OnInit {
  hasPermission = false;
  constructor() {

  }
  ngOnInit() {
    this.hasPermission = true;
  }
}

然后在您的按钮上创建局部变量并分配给导出的 hasPermission 指令,以便您可以从模板访问指令属性

<form>
    <input type="text" ngModel name="name" >
 <button #ref="hasPermission" appHaspermission  [disabled]="ref['hasPermission'] && (client.pristine || something else)" >Enable</button>
</form>

示例:https ://stackblitz.com/edit/angular-pebven


推荐阅读