angular - 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;
}
}
}
解决方案
使用可以在指令装饰器上使用 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>
推荐阅读
- javascript - 如何在 React 中渲染和更新来自父组件的子元素?
- python - 当我从另一个 QMainWindow 传递参数后要求另一个 QMainWindow 出现时,它没有出现?
- server - 我们如何响应客户端 h2c 升级请求,使用 nghttp2 库进行服务器实现
- javascript - chrome.runtime.sendMessage() 在 chrome 90.0.4430.93 macOS 上崩溃
- qt - 使用 DRM/GEM 的 VNC
- android - 寻找合适的 android 元素
- r - 计算点与R中某个值的最近栅格单元的距离
- javascript - JS 不会运行超过 set style.zIndex
- php - 当我使用 preg_match_all php 时,array_unique() 不起作用
- javascript - 将 algosigner chrome 扩展合并到 React 项目中