user9651431
user9651431

Reputation:

Property 'element' does not exist on type 'Directive'.ts

I'm facing the error property 'element' does not exists on 'directive'. Here I'm trying to create the directives functionalities.

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[Directive]'
})
export class Directive{

  constructor(element: ElementRef) {
    element.nativeElement.style.backgroundColor = 'brown';
    element.nativeElement.style.fontSize = '38px';
  }

  @HostListener('mouseenter') onmouseenter() {
    this.highlight('red');
  }
  @HostListener('mouseleave') onmouseleave() {
    this.highlight('yellow');
  }

  private highlight(color: string) {
    this.element.nativeElement.style.backgroundColor = color;
  }

}

Upvotes: 2

Views: 558

Answers (2)

Poul Kruijt
Poul Kruijt

Reputation: 71931

Your constructor parameter is only accessible inside the constructor at the moment, you need to add one of these access modifiers keywords: private, protected, public, or readonly to make it a class field:

constructor(readonly element: ElementRef) {}

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86790

The class name should be different from Directive

export class CustomDirective{ }

and at the time of initialization in the constructor, you must specify access modifiers like public , private etc, in order to use those within any method of that class.

Upvotes: 1

Related Questions