Home > Blockchain >  simple directive to add class doesn't work
simple directive to add class doesn't work

Time:01-06

I wand to add a class to a div based on two condidions. For this I created a directive like this:

import { Directive, HostBinding, Input } from '@angular/core';

@Directive({
  selector: '[confirmdialog-style]',
})
export class ConfirmDialogStyleDirective {
  @Input() isMsgDialog!: boolean;
  @Input() dialogType!: string;

  @HostBinding('class')
  elementClass = this.isMsgDialog ? 'x-'   this.dialogType : '';
}

And I use it like this:

<div
  
  confirmdialog-style
  [isMsgDialog]="isMsgDialog"
  [dialogType]="dialogType"
>

I set the isMsgDialog and dialogType properties in the parent component via button click. The two input properties are set correctly, as I checked it via chrome debug tools.

The issue is, that the desired class (f. e. x-danger) isn't added to the div. Why doesn't this work?

CodePudding user response:

Try this, so that the it takes into account isMsgDialog and dialogType changes:

    @HostBinding('class')
    get elementClass() {
        return this.isMsgDialog ? 'x-'   this.dialogType : '';
    }

CodePudding user response:

I find your code is good and I think it is necessary to verify isMsgDialog is not empty

  •  Tags:  
  • Related