是否有一种安全的方法来创建将封装类应用于输入标记的组件或指令,即<input com-input>?

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

我的目标是使用

input
标签与
selector[attribute]
而不是
selector
以避免使用主机组件包装
input

我更喜欢

selector[attribute]
而不是
selector]
,以避免重新发明轮子,即如果我想支持
autocomplete
,我必须使用
@Input() autocomplete: string = ""
,然后将其添加到
<com-input autocomplete='email'>

预期用途

    <input
      com-input
      #inputEmail
      autocomplete="username"
      (input)="email = inputEmail.nativeElement.value"
      [isError]="errorMessage ? true : false"
      placeholder="Email"
      type="email"
    />

问题是:

  1. 当我们添加属性即
    <input com-input>
    ,然后添加哈希符号即
    <input com-input #inputElement>
    时,
    inputElement
    类型变为
    InputComponent
    而不是
    HTMLInputElement
    。因此,我们无法访问输入值。

解决办法是:

  1. 实现
    ElementRef<HTMLInputElement>
    并将
    ElementRef
    注入
    InputComponent
    。然后,设置
    nativeElement
    属性。

但是,Angular 文档警告说 ElementRef 并不安全。所以,我很确定我的工作是黑客行为。

/* eslint-disable @angular-eslint/component-selector */
import { Component, ElementRef, HostBinding, Input } from '@angular/core';

@Component({
  selector: 'input[com-input]',
  standalone: true,
  imports: [],
  templateUrl: './input.component.html',
  styleUrl: './input.component.scss',
})
export class InputComponent implements ElementRef<HTMLInputElement> {
  nativeElement: HTMLInputElement;

  @HostBinding('class.error') @Input() isError: boolean = false;

  constructor(elementRef: ElementRef) {
    this.nativeElement = elementRef.nativeElement;
  }
}

javascript angular
1个回答
0
投票

您可以使用

read
@ViewChild
属性并直接从父级访问元素引用

在父母身上你可以给

@ViewChild('inputEmail', { read: Element ref }) inputEmail: Element ref<any>;

在 html 上只需给出

 <input
  com-input
  #inputEmail
  autocomplete="username"
  (input)="email = inputEmail.nativeElement.value"
  [isError]="errorMessage ? true : false"
  placeholder="Email"
  type="email"
/>
© www.soinside.com 2019 - 2024. All rights reserved.