具有反应性形式返回字符串而不是数字的角度自定义输入

发布于 2025-02-06 08:36:27 字数 440 浏览 2 评论 0原文

我有一个自定义的角度输入组件,该组件具有type输入属性要在​​输入元素上设置,该类型是联合类型。

// The custom input component
export InputType = 'text' | 'password' | 'number'

export class InputComponent {
   @Input() type: InputType
}

<input [type]="type">

// How I use it
<custom-input type="number"></custom-input>

我有一些问题可以在reactiveforms中使用此自定义输入。当我尝试获取表单值时,数字属性是字符串。相反,当我在数字上正确编码HTML输入中的类型编号时

I have a custom Angular input component which has an type input property to set it on the input element, the type is a union type.

// The custom input component
export InputType = 'text' | 'password' | 'number'

export class InputComponent {
   @Input() type: InputType
}

<input [type]="type">

// How I use it
<custom-input type="number"></custom-input>

I have some issue to use this custom input in ReactiveForms with numbers. When I try to get the form values the numeric properties are strings. Instead when I hard-coded the type number in the HTML input when values are correctly in numbers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌生 2025-02-13 08:36:27

解决的。上面的答案适用于“类型”属性以外的任何内容。解决此情况的唯一方法是使用具有预定义(常数)输入类型的不同 *NGIF块:

<input *ngIf="inputType === 'number'" type="number" >
<input *ngIf="!inputType || inputType === 'text'">
... etc.

RESOLVED. Answers above are suitable for anything except the 'type' attribute. The only method to resolve this case I found is to use different *ngIf blocks with predefined (constant) input types:

<input *ngIf="inputType === 'number'" type="number" >
<input *ngIf="!inputType || inputType === 'text'">
... etc.
嘦怹 2025-02-13 08:36:27

首先通过此命令创建组件:

ng GC定制输入

NG GC在TS组件中添加以下代码中的

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-custom-input',
  template: `<input [type]="InputType"/>`,
  styleUrls: ['./custom-input.component.scss']
})
export class CustomInputComponent implements OnInit {

  @Input() InputType: string='';

  constructor() { }

  ngOnInit(): void {
  }
}

:然后在子组件中使用它,如下:

  1. 数字输入:

    &lt; app-custom输入[inputType] =“'number'&gt;

  2. 文本输入:

    &lt; app-custom输入[inputType] =“'text'&gt;

  3. 和等...

First creat component by this command:

ng g c custom-input

in ts component add below codes:

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-custom-input',
  template: `<input [type]="InputType"/>`,
  styleUrls: ['./custom-input.component.scss']
})
export class CustomInputComponent implements OnInit {

  @Input() InputType: string='';

  constructor() { }

  ngOnInit(): void {
  }
}

Then use it in the child component as follows:

  1. number input:

    <app-custom-input [InputType]="'number'">

  2. text input:

    <app-custom-input [InputType]="'text'">

  3. and etc...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文