如何在 Angular 指令中将 ElementRef 转换为 HTMLFormElement
How to convert ElementRef to HTMLFormElement in Angular Directive
我正在尝试将 ElementRef 转换为 HTMLFormElement,它显示以下警告:
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.
代码:
@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]
听起来您正在尝试建立对 原生元素 的引用,而不是对 元素引用 的引用。我想你想要这个:
constructor(private form: ElementRef) {
console.log(<HTMLFormElement>form.nativeElement);
}
我正在尝试将 ElementRef 转换为 HTMLFormElement,它显示以下警告:
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.
代码:
@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]
听起来您正在尝试建立对 原生元素 的引用,而不是对 元素引用 的引用。我想你想要这个:
constructor(private form: ElementRef) {
console.log(<HTMLFormElement>form.nativeElement);
}