Angular: 未在指令中获取表单 pristine/invalid 状态的引用

Angular: not getting reference of Form pristine/invalid status inside directive

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

我该如何管理?

我想先检查权限,如果有,那么只有这个 pristine/invalid 会出现。请指导。

如果我获得此表单的 pristine/invalid 内部指令的状态,我相信我们可以管理它,但如何将其放入内部,我尝试了一些使用 DoCheck/Host 等 none 的解决方案me Form reference inside Directive.

我不想使用 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;
        }
    }
}

使用可以在指令上使用 exportAs 属性 decorator.Which 将公开 appHaspermission 指令实例。

The exportAs takes the name under which the component instance is exported in a template.

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