Deb
Deb

Reputation: 5649

How to convert ElementRef to HTMLFormElement in Angular Directive

I am trying to cast ElementRef to HTMLFormElement which shows the following warning: enter image description here

Conversion of type 'ElementRef' to type 'HTMLFormElement' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

Code:

@Directive({
  selector: '[appSlValidate]'
})
export class SlValidateDirective {
  @Input() appSlValidate: any;

  constructor(private form: ElementRef) { 
    console.log(<HTMLFormElement>form);
  }

}

Binding:

<form [appSlValidate]>

If I directly try to inject HTMLFormElement instead of ElementRef, I am getting this error:

NullInjectorError: StaticInjectorError(AppModule)[SlValidateDirective -> HTMLFormElement]: 
  StaticInjectorError(Platform: core)[SlValidateDirective -> HTMLFormElement]

Upvotes: 1

Views: 1646

Answers (1)

mwilson
mwilson

Reputation: 12910

It sounds like you're trying to establish a reference to the native element rather than to the element reference. I think you want this instead:

constructor(private form: ElementRef) { 
    console.log(<HTMLFormElement>form.nativeElement);
}

Upvotes: 3

Related Questions