0
votes

I have a form, dynamically fill on init (using database data).

I add a pattern check (using some REGEX). If the pattern isn't good, a mat-error is shown. It's working if I focus in and then focus out the input.

But the mat-error is not showing automatically if I use setValue() function from FormControl.

Here is the mat-error definition :

<input [id]="field.id" matInput type="text" [formControl]="field.control" [pattern]="field.pattern">
<mat-error class="mt-1" *ngIf="field.control.errors">
    {{ getErrorMessage(field.id, category['id']) }}
</mat-error>

and the way I set value automatically

async fillForm(data: any): Promise<any> {
    this.fields = data.fields;
    for (let category in this.fields) {
        for (let cpt in this.fields[category]) {
            let field = this.fields[category][cpt];
            this.form[category].push({
                id: field.id,
                label: field.label,
                required: field.required,
                control: new FormControl(),
                type: field.type,
                pattern: this.getPattern(field.format),
                color: field.color,
                unit: field.unit,
                class: field.class,
                format: field.format,
                display: field.display,
                format_icon: field.format_icon,
                display_icon: field.display_icon,
                class_label: field.class_label,
                cpt: 0,
            });

            let value = this.invoice.datas[field.id];
            let _field = this.form[category][this.form[category].length - 1];
            _field.control.setValue(value);
        }
    }
}

Thanks for your help

1

1 Answers

0
votes

Let's try this approach:

<input [id]="field.id" matInput type="text" [formControl]="field.control">
<mat-error class="mt-1" *ngIf="field.control.errors">
    {{ getErrorMessage(field.id, category['id']) }}
</mat-error>
async fillForm(data: any): Promise<any> {
    this.fields = data.fields;
    for (let category in this.fields) {
        for (let cpt in this.fields[category]) {
            let field = this.fields[category][cpt];
            let value = this.invoice.datas[field.id];
            this.form[category].push({
                id: field.id,
                label: field.label,
                required: field.required,
                control: new FormControl(value, [Validators.pattern(this.getPattern(field.format))]),
                type: field.type,
                pattern: this.getPattern(field.format),
                color: field.color,
                unit: field.unit,
                class: field.class,
                format: field.format,
                display: field.display,
                format_icon: field.format_icon,
                display_icon: field.display_icon,
                class_label: field.class_label,
                cpt: 0,
            });
        }
    }
}