提问人:Jinglemahn 提问时间:10/19/2023 更新时间:10/19/2023 访问量:62
为什么禁用时表单输入值不一致?
Why does the form input value is inconsistent when disabled?
问:
我目前正在 StorybookJS 中处理 Angular 输入组件。我面临的问题是,当我在 storybook js 的控制面板中键入 a(例如,hello)并单击 true 时,输入文本被禁用,显示文本“hello”,文本按预期保持禁用状态,并在 false 时恢复正常。这是正确的行为。value
disabled
disabled
但是,当我实际输入输入本身(例如,hello11)并重复类似的步骤时,当我单击true时,输入中的值将被更改并显示为“hello”而不是“hello11”。因此,在实际在文本输入本身中键入值并禁用它时,value 的输出存在一些不一致。disabled
这是我所拥有的:
在 input-test.component.html 中:
<input
type="text"
[(ngModel)]="value"
[disabled]="disabled"
(input)="updateValue($event)"
/>
在input-test.component.ts:
import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-input-test',
templateUrl: './input-test.component.html',
styleUrls: ['./input-test.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputTestComponent),
multi: true,
},
],
})
export class InputTestComponent implements ControlValueAccessor {
@Input() value: string = '';
@Input() disabled: boolean = false;
/**
* @ignore
*/
onChange: any = () => {};
/**
* @ignore
*/
onTouch: any = () => {};
writeValue(value: any): void {
this.value = value;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
updateValue(event: Event): void {
const newValue = (event.target as HTMLInputElement).value;
this.value = newValue;
this.onChange(this.value);
this.onTouch(this.value);
}
}
在InputTest.stories.ts:
import { FormsModule, ReactiveFormsModule, FormBuilder } from '@angular/forms';
import { InputTestComponent } from 'src/app/input-test/input-test.component';
import { Meta, StoryObj } from '@storybook/angular';
import { moduleMetadata } from '@storybook/angular';
const meta: Meta<InputTestComponent> = {
component: InputTestComponent,
title: 'Basic Components/InputTestComponent',
tags: ['autodocs'],
decorators: [
moduleMetadata({
declarations: [InputTestComponent],
imports: [FormsModule, ReactiveFormsModule],
}),
],
args: {},
render: (args: InputTestComponent) => ({
props: {
...args,
},
}),
argTypes: {},
};
export default meta;
type Story = StoryObj<InputTestComponent>;
const createFormGroup = (value: string, disabled: boolean) => {
const fb = new FormBuilder();
return fb.group({
name: [{value: value, disabled: disabled}],
});
};
export const Default: Story = {
args: {
value: 'default',
disabled: false,
},
render: (args) => ({
props: {
...args,
form: createFormGroup(args.value, args.disabled),
},
template: `
<form [formGroup]="form">
<app-input-test formControlName="name" [(ngModel)]="value" [disabled]="disabled"></app-input-test>
</form>
<div>Name: {{ form.get('name').value }}</div>
`,
}),
};
有人可以帮我解决这个问题吗?谢谢!
答:
0赞
Eliseo
10/19/2023
#1
value
不是一个简单的变量。@Input
- 您无需更改函数中的变量
this.value
updateValue
disabled
不是@Input
- 您需要实现
[setDisabledState]
方法
评论