Search code examples
angulartypescriptangularjs-directive

How can i pass conditional variables in custom directive Angular?


I am trying to pass variable in my custom directive. But this gets false or undefined after load. Please help me to find the issue and guide me where i am wrong.

Custom Directive

import { Directive, ElementRef, Renderer2, AfterViewInit, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[air-btn]'
})
export class AirBtnDirective implements OnInit {

  @Input() small?: boolean;
  @Input() outline?: boolean;

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

  classes: string[] = [
    'relative',
    'disabled:opacity-70',
    'disabled:cursor-not-allowed',
    'rounded-lg',
    'hover:opacity-80',
    'transition',
    'w-full',
    this.outline ? 'bg-white' : 'bg-rose-500',
    this.outline ? 'border-black' : 'border-rose-500',
    this.outline ? 'text-black' : 'text-white',
    this.small ? 'text-sm' : 'text-md',
    this.small ? 'py-1' : 'py-3',
    this.small ? 'py-1' : 'py-3',
    this.small ? 'font-light' : 'font-semibold',
    this.small ? 'border-[1px]' : 'border-2'
  ]

  ngOnInit(): void {
    console.log(this.outline)
    this.classes.forEach((val) => {
      this.renderer.addClass(this.el.nativeElement, val);
    })
  }
}

HTML

<button air-btn [outline]="true">Continue with Google</button>

Any solution appreciated!


Solution

  • You should initialize the classes array inside ngOnInit.

    import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
    
    @Directive({
      selector: '[air-btn]'
    })
    export class AirBtnDirective implements OnInit {
      @Input() small?: boolean;
      @Input() outline?: boolean;
    
      constructor(private el: ElementRef, private renderer: Renderer2) {}
    
      classes: string[] = [];
    
      ngOnInit(): void {
        this.classes = [
          'relative',
          'disabled:opacity-70',
          'disabled:cursor-not-allowed',
          'rounded-lg',
          'hover:opacity-80',
          'transition',
          'w-full',
          this.outline ? 'bg-white' : 'bg-rose-500',
          this.outline ? 'border-black' : 'border-rose-500',
          this.outline ? 'text-black' : 'text-white',
          this.small ? 'text-sm' : 'text-md',
          this.small ? 'py-1' : 'py-3',
          this.small ? 'py-1' : 'py-3',
          this.small ? 'font-light' : 'font-semibold',
          this.small ? 'border-[1px]' : 'border-2',
        ];
        console.log(this.outline);
        this.classes.forEach((val) => {
          this.renderer.addClass(this.el.nativeElement, val);
        });
      }
    }