I am working on a simple input field using Angular which is running in StorybookJS. The problem that I am facing is that, the input text field is not retaining its value when disabled
is set to true.
So what is happening is that when I type "hello" text manually into the input field as follows:
And when I set the disabled
property to true
, the input field is disabled but, not retaining the value "hello" and instead, it is showing an empty text which is not correct.
Nonetheless, below the code to which I described above.
In input.component.html
<input [formControl]="inputValue" />
<div *ngIf="inputValue.invalid && inputValue.touched">
<small *ngIf="inputValue.errors" class="error-text">This field is required.</small>
</div>
In input.component.ts
import { Component, Input } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent {
@Input() value: string = '';
@Input() disabled: boolean = false;
// Create a FormControl to handle the input value and validation
inputValue: FormControl = new FormControl();
constructor() {}
ngOnInit(): void {
this.inputValue = new FormControl(
{ value: this.value, disabled: this.disabled },
[Validators.required]
);
}
}
In Input.stories.ts
import { InputComponent } from './../../app/input/input.component';
import { Meta, StoryObj } from '@storybook/angular';
import { moduleMetadata } from '@storybook/angular';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
const meta: Meta<InputComponent> = {
component: InputComponent,
title: 'Basic Components/InputComponent',
tags: ['autodocs'],
decorators: [
moduleMetadata({
declarations: [InputComponent],
imports: [FormsModule, ReactiveFormsModule],
}),
],
args: {},
render: (args: InputComponent) => ({
props: {
...args,
},
}),
argTypes: {},
};
export default meta;
type Story = StoryObj<InputComponent>;
export const Default: Story = {
args: {
value: '',
disabled: false,
},
render: (args) => ({
props: {
...args,
},
template: `
<form>
<app-input [value]="value" [disabled]="disabled"></app-input>
<!-- Adding an error message display in the story -->
<div *ngIf="!value && value !== null">
<small class="error-text">This field is required.</small>
</div>
</form>
`,
}),
};
Can I get some help on this to why the input text field is not retaining the entered value when disabled? Thank you.