2
votes

I'm trying to write a custom directive that will set a button to disabled (and perform other logic) for a button that is contained within a mat-menu. I've removed a lot of the code for simplicity but take my HTML template here

<mat-menu #editMenu="matMenu">
    <ng-template matMenuContent>
      <button
        mat-menu-item
        myCustomDirective>
        Button Number 1
      </button>
      <button mat-menu-item>
        Button Number 2
      </button>
    </ng-template>
</mat-menu>

Now here is my custom directive which is very simple

@Directive({
    selector: '[myCustomDirective]'
})
export class MyCustomDirective implements OnInit {

constructor(public renderer: Renderer2, public el: ElementRef) {}

ngOnInit() {
// set the item to disabled... logic has been removed for example
this.renderer.setAttribute(this.el.nativeElement, 'disabled', true);
}

Now my custom directive doesn't work or it seems to be overwritten / rendered by the mat-menu-item directive. Should I move the mat-menu-item my custom directive works perfectly. In AngularJS you could order directive but I am unsure if I can do this in Angular 6. I have tried using setTimeout to delay my directive after the mat-menu-item has rendered but this doesn't work either. Does anyone know how I can get both directives to work on the same HTML element?

Many thanks in advance.

UPDATE

I tried to use @HostBindingin my custom directive, like so

@HostBinding('attr.disabled') disabledAttribute: boolean;

ngOnInit() {
    this.disabledAttribute = true;
  }

but this doesn't seem to work either.

1

1 Answers

0
votes

Try this alternative

Since mat-menu-item directive has disabled input property you can access the disabled property using template ref and pass to the customDirective as a Input and set disable dynamically

<mat-menu #editMenu="matMenu" >
    <ng-template matMenuContent >
      <button #ref [appCustomDirective]="ref"
        mat-menu-item
        >
        Button Number 1
      </button>
      <button #ref2 mat-menu-item [appCustomDirective]="ref2">
        Button Number 2
      </button>
    </ng-template>
</mat-menu>

Example