I'm encountering a puzzling issue. A directive needs to be implemented that enables or disables UI elements based on the user's role. While it works for UI elements that are not disabled by any other conditions, some buttons become disabled when just one of multiple conditions is met. These conditions can change as the user interacts with the page.
// Directive
@Directive({
selector: '[roleDisable]',
})
export class RoleDisableDirective implements OnInit, OnChanges {
@Input('roleDisable') role: string;
@HostBinding('disabled') disabled: string;
constructor(
private store: Store<fromApp.AppState>,
private elementRef: ElementRef,
private renderer: Renderer2
) {}
ngOnInit() {
this.checkRights();
}
ngOnChanges() {
this.checkRights();
}
private checkRights(): void {
this.store.select(fromClient.hasNeededRole, {role: this.role }) //Observable<string>
.pipe(take(1))
.subscribe(hasRole => {
// Attempted to remove [disabled], but does not work
if (element.hasAttribute('disabled')) {
this.renderer.removeAttribute(element, 'disabled');
}
this.disabled = hasRole; // this works
});
}
}
// Usage in component template
<button
roleDisable="start_process"
mat-raised-button
(click)="startProcess()"
[disabled]="
!processEnabled ||
isUnavailable ||
hasInputs ||
preparationRunning ||
"
>
If I remove the [disabled]
property with all the conditions, the button becomes disabled, indicating that the directive is functioning correctly. However, keeping the [disabled]
calculation and having no condition evaluate to true
results in the directive being overridden and the button becoming enabled, which is not the intended behavior.
How can I ensure that the directive successfully overrides/removes the [disabled]
property calculation? Attempts to delete [disabled]
before re-enabling it had no effect. Any suggestions?