0
votes

I have a form with 3 inputs, 2 of the inputs are required and the third isn't.

My problem is that when I go the page of the form I see that the field that isn't required is in a valid state and is already colored with green, even tho the field isn't dirty or touched.

Is there anything I can do to make the input be grayed out until I validate the field / form or is it like this by design?

Here's the code I use in the component:

export class SystemSettingsComponent implements OnInit {
form: FormGroup;

constructor(private formBuilder: FormBuilder) {
    this.form = new FormGroup({});
}

ngOnInit() {
    this.form = this.formBuilder.group({
        serviceName: ['', Validators.required],
        serviceDesc: [''],
        serviceId: [{value: SystemSettingsComponent.generateId(), disabled: true}, Validators.required]
    });
}

static generateId() {
    return Math.random().toString(36).substr(2, 9);
}}

And the template :

<form [formGroup]="form" novalidate>
<div class="row">
    <div class="col-lg-4">
        <mat-form-field>
            <input matInput placeholder="שם השירות" formControlName="serviceName"/>
        </mat-form-field>
        <mat-form-field>
            <textarea matInput placeholder="תיאור השירות" formControlName="serviceDesc"></textarea>
        </mat-form-field>
        <mat-form-field>
            <input matInput class="ltr text-align-left" placeholder="מזהה שירות" formControlName="serviceId"/>
        </mat-form-field>
    </div>
</div>
<div>
    <button mat-raised-button class="mat-raised-button mat-primary" matStepperNext>הבא</button>
</div>

1
Why you are not using ngForm they are easy enough to validate.. - Yashwardhan Pauranik

1 Answers

0
votes

You can listen to the form's status changes and set the optional form control's disabled state accordingly. Something like:

ngOnInit() {
    this.form = this.formBuilder.group({
        serviceName: ['', Validators.required],
        serviceDesc: [{value: '', disabled: true}],
        serviceId: [{value: SystemSettingsComponent.generateId(), disabled: true}, Validators.required]
    });

    this.form.statusChanges.subscribe(status => {
        if (status === 'VALID' && this.form.controls.serviceDesc.disabled) {
            this.form.controls.serviceDesc.enable();
        } else if (status !== 'VALID' && this.form.controls.serviceDesc.enabled) {
            this.form.controls.serviceDesc.disable();
        }
    });
}