我正在尝试将ElementRef强制转换为HTMLFormElement,它显示以下警告:
将类型'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]
听起来好像您正在尝试建立对native element的引用,而不是对element reference的引用。我认为您想要这样:
constructor(private form: ElementRef) {
console.log(<HTMLFormElement>form.nativeElement);
}