double-field.component.ts (1-336) import {… · The Chat Archive
Explore / Programming double-field.component.ts (1-336) import { ChangeDetectionStrategy, Component,… Save Share Download ▾ Reportdouble-field.component.ts (1-336)
import {
ChangeDetectionStrategy,
Component,
DestroyRef,
OnInit,
inject,
input,
output,
signal,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { fieldGeneratorMap, GeneratorType } from '../schema-config.model';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { SchemaFormFieldGeneratorService } from '../../shared/services/schema-form-field-generator.service';
import { compareToOtherFieldValidator } from '../../shared/validators/compare-to-other-field-validator.validator';
import { numbersCommaSeparatedValidator } from '../../shared/validators/numbers-comma-separate-validator.validator';
import { startWith } from 'rxjs';
import { matchingArrayLengthsValidator } from '../../shared/validators/matching-array-lenghts-validator.validator';
import { TitleCasePipe } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { RepeatMaskDirective } from '../../shared/directives/repeat-mask.directive';
import { ErrorMessagePipe } from '../../shared/pipes/error-message.pipe';
type DoubleFieldGenerator =
| { type: GeneratorType.Uniform; min: number; max: number }
| { type: GeneratorType.Normal; mean: number; std_dev: number }
| { type: GeneratorType.Enum; values: number[]; weights: number[] }
| { type: GeneratorType.NumericRange; start: number; step: number }
| { type: GeneratorType.Values; values: number[] };
interface DoubleFieldForm {
type: FormControl;
min?: FormControl;
max?: FormControl;
mean?: FormControl;
stdDev?: FormControl;
values?: FormControl;
weights?: FormControl;
start?: FormControl;
step?: FormControl;
}
@Component({
selector: 'app-double-field',
standalone: true,
imports: [
MatFormFieldModule,
MatSelectModule,
ReactiveFormsModule,
MatInputModule,
ReactiveFormsModule,
TitleCasePipe,
MatIconModule,
MatButtonModule,
RepeatMaskDirective,
ErrorMessagePipe,
],
templateUrl: './double-field.component.html',
styleUrl: './double-field.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DoubleFieldComponent implements OnInit {
private readonly schemaFormFieldGeneratorSvc = inject(
SchemaFormFieldGeneratorService,
);
private readonly destroyRef = inject(DestroyRef);
public readonly autoRenew = signal(true);
public generatorTypes =
input.required();
public changeField = output<{
schema: DoubleFieldGenerator | undefined;
valid: boolean;
}>();
private matchingValuesWeightsValidator = matchingArrayLengthsValidator([
'weights',
]);
private matchingWeightsValuesValidator = matchingArrayLengthsValidator([
'values',
]);
public type = this.schemaFormFieldGeneratorSvc.getTypeField();
public min = this.schemaFormFieldGeneratorSvc.getMinField({
value: 1.0,
validators: [
Validators.min(Number.MIN_SAFE_INTEGER),
compareToOtherFieldValidator(
'max',
(min: number, max: number) => +min < +max,
'minGreaterThanMax',
),
],
});
public max = this.schemaFormFieldGeneratorSvc.getMaxField({
value: 100.0,
validators: [
Validators.max(Number.MAX_SAFE_INTEGER),
compareToOtherFieldValidator(
'min',
(max: number, min: number) => +min < +max,
'MaxSmallerThanMin',
),
],
});
public mean = this.schemaFormFieldGeneratorSvc.getMeanField({
value: 0.0,
});
public stdDev = this.schemaFormFieldGeneratorSvc.getStdDevField({
value: 1.0,
});
public values = this.schemaFormFieldGeneratorSvc.getValuesField({
validators: [numbersCommaSeparatedValidator],
});
public weights = this.schemaFormFieldGeneratorSvc.getWeightsField();
public start = this.schemaFormFieldGeneratorSvc.getStartField({
value: 1.0,
});
public step = this.schemaFormFieldGeneratorSvc.getStepField({
value: 1.0,
});
public fieldForm = new FormGroup({
type: this.type,
});
Show full message · 813 lines Assistant2024-10-22 08:18 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 22, 2024
Added to archive Nov 16, 2026
ID 01m7h41zd7wzhsq0sr1xfkn23zSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: f9a6856b5849c29a594c0cea544b2689
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
public ngOnInit(): void {
this.type.valueChanges
.pipe(startWith(this.type.value), takeUntilDestroyed(this.destroyRef))
.subscribe((type) => {
this.updateFormControls(type);
});
code Copy code
this.fieldForm.valueChanges
.pipe(
startWith(this.fieldForm.value),
takeUntilDestroyed(this.destroyRef),
)
.subscribe(() => {
const schema = this.getTypedFormValue();
if (schema)
this.changeField.emit({
schema,
valid: this.fieldForm.valid,
});
});
this.min.valueChanges
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.max.updateValueAndValidity({ emitEvent: false });
});
this.max.valueChanges
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.min.updateValueAndValidity({ emitEvent: false });
});
this.values.valueChanges
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
if (this.autoRenew() && this.values.valid) this.updateWeights();
});
this.weights.valueChanges
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.values.updateValueAndValidity({ emitEvent: false });
});
private updateFormControls(type: GeneratorType): void {
switch (type) {
case GeneratorType.Uniform:
this.fieldForm.removeControl('values');
this.fieldForm.removeControl('weights');
this.fieldForm.removeControl('start');
this.fieldForm.removeControl('step');
this.fieldForm.removeControl('mean');
this.fieldForm.removeControl('stdDev');
code Copy code
this.fieldForm.addControl('min', this.min);
this.fieldForm.addControl('max', this.max);
break;
case GeneratorType.Enum:
this.fieldForm.removeControl('min');
this.fieldForm.removeControl('max');
this.fieldForm.removeControl('start');
this.fieldForm.removeControl('step');
this.fieldForm.removeControl('mean');
this.fieldForm.removeControl('stdDev');
this.fieldForm.addControl('values', this.values);
this.fieldForm.addControl('weights', this.weights);
this.updateValuesAndWeightsValidation();
break;
case GeneratorType.Normal:
this.fieldForm.removeControl('values');
this.fieldForm.removeControl('weights');
this.fieldForm.removeControl('start');
this.fieldForm.removeControl('step');
this.fieldForm.removeControl('min');
this.fieldForm.removeControl('max');
this.fieldForm.addControl('mean', this.mean);
this.fieldForm.addControl('stdDev', this.stdDev);
break;
case GeneratorType.NumericRange:
this.fieldForm.removeControl('min');
this.fieldForm.removeControl('max');
this.fieldForm.removeControl('values');
this.fieldForm.removeControl('weights');
this.fieldForm.removeControl('mean');
this.fieldForm.removeControl('stdDev');
this.fieldForm.addControl('start', this.start);
this.fieldForm.addControl('step', this.step);
break;
case GeneratorType.Values:
this.fieldForm.removeControl('min');
this.fieldForm.removeControl('max');
this.fieldForm.removeControl('weights');
this.fieldForm.removeControl('start');
this.fieldForm.removeControl('step');
this.fieldForm.removeControl('mean');
this.fieldForm.removeControl('stdDev');
this.fieldForm.addControl('values', this.values);
this.values.removeValidators(this.matchingValuesWeightsValidator);
break;
}
}
private getTypedFormValue(): DoubleFieldGenerator | undefined {
const { type, min, max, mean, stdDev, values, weights, start, step } =
this.fieldForm.value;
code Copy code
switch (type) {
case GeneratorType.Uniform:
if (min && max) return { type, min: +min, max: +max };
break;
case GeneratorType.Enum:
if (values && weights)
return {
type,
values: values.split(',').map((v) => +v.trim()),
weights: weights.split(',').map((v) => parseFloat(v)),
};
break;
case GeneratorType.Normal:
if (mean && stdDev) return { type, mean: +mean, std_dev: +stdDev };
break;
case GeneratorType.NumericRange:
if (start && step)
return {
type,
start: +start,
step: +step,
};
break;
case GeneratorType.Values:
if (values)
return {
type,
values: values.split(',').map((v) => +v.trim()),
};
break;
}
return undefined;
private calculateWeights(values: string): string {
const valueArray = values
.split(',')
.map((v) => v.trim())
.filter((v) => v !== '');
code Copy code
if (valueArray.length === 0) return '';
const weight = (1 / valueArray.length).toFixed(2);
return Array(valueArray.length).fill(weight).join(', ');
private updateValuesAndWeightsValidation(): void {
if (this.autoRenew()) {
this.values.removeValidators(this.matchingValuesWeightsValidator);
this.weights.removeValidators(this.matchingWeightsValuesValidator);
} else {
this.values.addValidators(this.matchingValuesWeightsValidator);
this.weights.addValidators(this.matchingWeightsValuesValidator);
}
code Copy code
this.values.updateValueAndValidity({ emitEvent: false });
this.weights.updateValueAndValidity({ emitEvent: false });
private updateWeights(): void {
const calculatedWeights = this.calculateWeights(this.values.value || '');
this.weights.setValue(calculatedWeights, { emitEvent: true });
}
public onToggleAutorenew(): void {
this.autoRenew.update((value) => !value);
code Copy code
this.updateValuesAndWeightsValidation();
if (this.autoRenew()) this.updateWeights();
double-field.component.html (1-125)
@if (fieldForm.get("min")) {
Minimum Value
Enter the minimum value of the range
{{ fieldForm.get("min") | appErrorMessage }}
}
@if (fieldForm.get("max")) {
Maximum Value
Enter the maximum value of the range
{{ fieldForm.get("max") | appErrorMessage }}
}
@if (fieldForm.get("mean")) {
Mean
Enter the average value (mean) for the normal distribution
{{ fieldForm.get("mean") | appErrorMessage }}
}
@if (fieldForm.get("stdDev")) {
Standard Deviation
Enter the standard deviation for the normal distribution
{{ fieldForm.get("stdDev") | appErrorMessage }}
}
@if (fieldForm.get("values")) {
Values
Enter numeric values separated by commas
{{ fieldForm.get("values") | appErrorMessage }}
}
@if (fieldForm.get("weights")) {
Weights
<input
[readonly]="autoRenew()"
placeholder="e.g., 0.3, 0.3, 0.4"
matInput
formControlName="weights"
/>
Enter decimal weights between 0.0 and 1.0, separated by commas. The
weights should sum to 1.0.
{{ fieldForm.get("weights") | appErrorMessage }}
<button (click)="onToggleAutorenew()" matIconSuffix mat-icon-button>
{{ autoRenew() ? "autorenew" : "pause" }}
}
@if (fieldForm.get("start")) {
Start
Enter the starting value of the sequence
{{ fieldForm.get("start") | appErrorMessage }}
}
@if (fieldForm.get("step")) {
Step
Enter the step size to increment or decrement the value
{{ fieldForm.get("step") | appErrorMessage }}
}
schema-form-field-generator.service.ts (1-339)
import { Injectable } from '@angular/core';
import {
FormArray,
FormControl,
FormGroup,
ValidatorFn,
Validators,
} from '@angular/forms';
import {
FieldTypes,
GeneratorType,
} from '../../schema-config/schema-config.model';
import {
SchemaConfigForm,
SchemaFieldFormGroup,
} from '../interfaces/schema.interface';
import { weightsSumToOneValidator } from '../validators/weights-sum-to-one-validator.validator';
import { numbersCommaSeparatedValidator } from '../validators/numbers-comma-separate-validator.validator';
interface FormControlOptions {
value?: T;
validators?: ValidatorFn[];
}
@Injectable({
providedIn: 'root',
})
export class SchemaFormFieldGeneratorService {
private createFormControl(
defaultValue: T,
validators: ValidatorFn[] = [],
): FormControl {
return new FormControl(defaultValue, {
nonNullable: true,
validators: [...validators],
});
}
public getScaleField(
options: FormControlOptions = {},
): FormControl {
const validators = [
Validators.required,
Validators.pattern(/^[1-9]\d*$/),
...(options.validators || []),
];
code Copy code
return this.createFormControl<number>(options.value ?? 1, validators);
public getTypeField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<GeneratorType>(
options.value ?? GeneratorType.Uniform,
validators,
);
public getMinField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<number>(options.value ?? 1, validators);
public getMaxField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<number>(options.value ?? 100, validators);
public getMeanField(
options: FormControlOptions = {},
): FormControl {
const validators = [
Validators.required,
Validators.min(0),
...(options.validators || []),
];
code Copy code
return this.createFormControl<number>(options.value ?? 0, validators);
public getStdDevField(
options: FormControlOptions = {},
): FormControl {
const validators = [
Validators.required,
Validators.min(0),
...(options.validators || []),
];
code Copy code
return this.createFormControl<number>(options.value ?? 1, validators);
public getValuesField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<string>(options.value ?? '', validators);
public getWeightsField(
options: FormControlOptions = {},
): FormControl {
const validators = [
Validators.required,
numbersCommaSeparatedValidator,
weightsSumToOneValidator,
...(options.validators || []),
];
code Copy code
return this.createFormControl<string>(options.value ?? '', validators);
public getStartField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<number>(options.value ?? 1, validators);
public getEndField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<number>(options.value ?? 1, validators);
public getStartTimeField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<string>(
options.value ?? '000000',
validators,
);
public getEndTimeField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<string>(
options.value ?? '235959',
validators,
);
public getStartDateField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
const today = new Date();
today.setHours(0, 0, 0, 0);
code Copy code
return this.createFormControl<Date>(options.value ?? today, validators);
public getEndDateField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
const nextWeek = new Date();
nextWeek.setHours(0, 0, 0, 0);
nextWeek.setDate(nextWeek.getDate() + 7);
code Copy code
return this.createFormControl<Date>(options.value ?? nextWeek, validators);
public getStartDateTimeField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
const now = new Date();
const startDateTime = this.formatLocalDateTime(now);
code Copy code
return this.createFormControl<string>(
options.value ?? startDateTime,
validators,
);
public getEndDateTimeField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
const endDate = new Date();
endDate.setDate(endDate.getDate() + 7);
const endDateTime = this.formatLocalDateTime(endDate);
code Copy code
return this.createFormControl<string>(
options.value ?? endDateTime,
validators,
);
public getStartTimeStampField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
const now = new Date();
const startTimestamp = now.toISOString();
code Copy code
return this.createFormControl<string>(
options.value ?? startTimestamp,
validators,
);
public getEndTimestampField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
const endDate = new Date();
endDate.setDate(endDate.getDate() + 7);
const endTimestamp = endDate.toISOString();
code Copy code
return this.createFormControl<string>(
options.value ?? endTimestamp,
validators,
);
public getStepField(
options: FormControlOptions = {},
): FormControl {
const validators = [
Validators.required,
Validators.pattern(/^-?(?!0(?:.0+)?) \d ∗ ? ˙ \d + )\d*\.?\d+ ) \d ∗ ? ˙ \d + /),
...(options.validators || []),
];
code Copy code
return this.createFormControl<number>(options.value ?? 1, validators);
public getDurationField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<string>(options.value ?? '1 day', validators);
public getDescriptionField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<string>(options.value ?? '', validators);
public getTimePatternField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<string>(
options.value ?? 'HH:mm:ss',
validators,
);
public getDatePatternField(
options: FormControlOptions = {},
): FormControl {
const validators = [Validators.required, ...(options.validators || [])];
code Copy code
return this.createFormControl<string>(
options.value ?? 'yyyy-MM-dd',
validators,
);
public getSchemaConfigForm(
isArray: boolean = false,
isOptional: boolean = false,
): FormGroup {
return new FormGroup({
generatorsArray: new FormArray([
this.getGeneratorArray(isArray, isOptional),
]),
});
}
public getGeneratorArray(
isArray: boolean = false,
isOptional: boolean = false,
): FormGroup {
const group: Partial = {
type: new FormControl<FieldTypes | null>(null, {
validators: [Validators.required],
}),
schema: new FormControl<Record<string, any> | null>({}),
arrayLength: new FormControl(3, {
nonNullable: true,
validators: [Validators.required, Validators.min(0)],
}),
nullProbability: new FormControl(0.5, {
nonNullable: true,
validators: [Validators.required, Validators.min(0), Validators.max(1)],
}),
};
code Copy code
if (!isArray && !isOptional) {
group.name = new FormControl('', {
nonNullable: true,
validators: [Validators.required],
});
}
return new FormGroup(group as SchemaFieldFormGroup);
private formatLocalDateTime(date: Date): string {
const pad = (n: number) => (n < 10 ? '0' + n : n.toString());
code Copy code
const year = date.getFullYear();
const month = pad(date.getMonth() + 1);
const day = pad(date.getDate());
const hours = pad(date.getHours());
const minutes = pad(date.getMinutes());
const seconds = pad(date.getSeconds());
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
Do you have any idea why i'm seeing the integer number instead of the whole decimal in the html? When i enter on double field instead of 1.0 for Minimum value i see 1
The issue you're encountering stems from how JavaScript handles numeric values and how HTML input fields display them. In JavaScript, 1.0 and 1 are treated as the same numerical value (1). Consequently, when you input 1.0 into a number-based input field, it gets interpreted and displayed as 1.
To display the value with the decimal (e.g., 1.0) as entered by the user, you need to handle the value as a string rather than a number . This approach allows you to preserve and display the exact input format, including trailing zeros.
Here's a step-by-step guide to achieve this:
Update Form Controls to Use string Instead of number
Modify the form controls for fields where preserving decimal places is essential (e.g., min, max, mean, stdDev, etc.) to use string instead of number.
typescript Copy code
// double-field.component.ts
// Modify the DoubleFieldForm interface
interface DoubleFieldForm {
type: FormControl<GeneratorType>;
min?: FormControl<string>;
max?: FormControl<string>;
mean?: FormControl<string>;
stdDev?: FormControl<string>;
values?: FormControl<string>;
weights?: FormControl<string>;
start?: FormControl<string>;
step?: FormControl<string>;
}
Adjust the SchemaFormFieldGeneratorService to Return String-Based Form Controls
Update the service methods to return FormControl<string> for the relevant fields. This change allows the input fields to handle and display decimal points as entered.
typescript Copy code
// schema-form-field-generator.service.ts
public getMinField(
options: FormControlOptions<string> = {},
): FormControl<string> {
const validators = [
Validators.required,
Validators.pattern(/^-?\d+(\.\d+)?$/), // Adjusted regex to accept decimals
...(options.validators || []),
];
return this.createFormControl<string>(options.value ?? '1.0', validators);
}
public getMaxField(
options: FormControlOptions<string> = {},
): FormControl<string> {
const validators = [
Validators.required,
Validators.pattern(/^-?\d+(\.\d+)?$/), // Adjusted regex to accept decimals
...(options.validators || []),
];
return this.createFormControl<string>(options.value ?? '100.0', validators);
}
// Similarly, update other relevant fields like getMeanField, getStdDevField, etc.
Update the Component to Handle String Values and Convert Them to Numbers When Necessary
Since the form now handles string inputs, you'll need to parse these strings to numbers when processing or emitting the form values.
typescript Copy code
// double-field.component.ts
private getTypedFormValue(): DoubleFieldGenerator | undefined {
const { type, min, max, mean, stdDev, values, weights, start, step } = this.fieldForm.value;
switch (type) {
case GeneratorType.Uniform:
if (min && max) return { type, min: parseFloat(min), max: parseFloat(max) };
break;
case GeneratorType.Enum:
if (values && weights)
return {
type,
values: values.split(',').map((v) => parseFloat(v.trim())),
weights: weights.split(',').map((v) => parseFloat(v)),
};
case GeneratorType.Normal:
if (mean && stdDev) return { type, mean: parseFloat(mean), std_dev: parseFloat(stdDev) };
break;
case GeneratorType.NumericRange:
if (start && step)
return {
type,
start: parseFloat(start),
step: parseFloat(step),
};
break;
case GeneratorType.Values:
if (values)
return {
type,
values: values.split(',').map((v) => parseFloat(v.trim())),
};
}
return undefined;
}
Ensure Validation and Formatting Are Consistent
With the form controls now handling strings, make sure that all validators are adjusted accordingly to validate string inputs. This includes pattern validators that accept decimal numbers and any custom validators that might need to parse the string to perform their logic.
Additionally, update any methods that might manipulate these values to account for the string format before performing numerical operations.
Optional: Enhance User Experience with Input Formatting
While handling the input as a string allows you to preserve the decimal, you might want to ensure that the user experience remains seamless. Consider adding visual cues or helper text to inform users that the input accepts decimal values and that trailing zeros will be preserved.
html Copy code
<!-- double-field.component.html -->
<mat-form-field class="w-100">
<mat-label>Minimum Value</mat-label>
<input matInput formControlName="min" placeholder="e.g., 1.0" type="text" />
<mat-hint>Enter the minimum value of the range (e.g., 1.0)</mat-hint>
<mat-error>{{ fieldForm.get("min") | appErrorMessage }}</mat-error>
</mat-form-field>
Consider Using a Custom Directive or Pipe for Advanced Formatting (Optional)
If you require more advanced formatting or validation, you can implement a custom directive or pipe to handle number formatting within the input fields. This approach provides greater control over how values are displayed and processed.
typescript Copy code
// Example: number-format.directive.ts
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appNumberFormat]'
})
export class NumberFormatDirective {
constructor(private ngControl: NgControl) {}
@HostListener('blur') onBlur() {
const value = this.ngControl.control?.value;
if (value !== null && value !== undefined && value !== '') {
const formattedValue = parseFloat(value).toFixed(1);
this.ngControl.control?.setValue(formattedValue, { emitEvent: false });
}
}
}
html Copy code
<!-- Usage in HTML -->
<input matInput formControlName="min" placeholder="e.g., 1.0" type="text" appNumberFormat />
This directive formats the input value to one decimal place when the input field loses focus, ensuring consistency in how numbers are displayed.
Final Thoughts
By handling the input as a string, you maintain the exact representation entered by the user, including any trailing decimals. This approach ensures that 1.0 remains distinct from 1, addressing the visibility issue in your form. However, remember to parse these string values back to numbers when performing any calculations or data processing to maintain data integrity.
If you need further assistance implementing these changes or have additional questions, feel free to ask!
Copy first response
Not yet included in a published release.