如何在Angular指令中将ElementRef转换为HTMLFormElement

问题描述 投票:1回答:1

我正在尝试将ElementRef强制转换为HTMLFormElement,它显示以下警告:enter image description here

将类型'ElementRef'转换为类型'HTMLFormElement'可能是这是一个错误,因为两种类型都无法充分重叠。如果这是故意的,请先将表达式转换为“未知”。

代码:

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

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

}

绑定:

<form [appSlValidate]>

如果直接尝试注入HTMLFormElement而不是ElementRef,则会收到此错误:

NullInjectorError: StaticInjectorError(AppModule)[SlValidateDirective -> HTMLFormElement]: 
  StaticInjectorError(Platform: core)[SlValidateDirective -> HTMLFormElement]
angular angular-directive
1个回答
3
投票

听起来好像您正在尝试建立对native element的引用,而不是对element reference的引用。我认为您想要这样:

constructor(private form: ElementRef) { 
    console.log(<HTMLFormElement>form.nativeElement);
}
© www.soinside.com 2019 - 2024. All rights reserved.