Angular2 Reactive forms, FormControl default value in pristine status

1.9k views Asked by At

I have created a form which allows the user to add additional text-inputs by clicking a button. The FormControls behind these inputs are stored in a FormArray inside of a FormGroup.

I want to provide a default value for these inputs, that is going to be submitted if they are pristine. If the user changes the value of the input, which changes it to dirty, I do not want the default value to be submitted or displayed.

I currently am displaying the inputs like this, as the placeholder attribute does exactly what I want, displaying the default name, only if the input has not been changed.

<div
    formArrayName="names" 
    *ngFor="let server of names.controls; let i = index; trackBy:trackByFn">
        <span>{{ i + 1 }}</span>
        <input 
        type="text" 
        formControlName="{{i}}"
        placeholder="{{defaultName}}">

</div>

To validate the names I have created the following validation function:

export function validateServerName(form: FormGroup): ValidationErrors | null {
    const names: string[] = form.value[CREATE_FORM_KEY_NAMES];

    for (const name of names) {
        if (name.trim() === '') {
            return {
                invalidName: true
            };
        }
    }

    return null;
}

Here I am having trouble figuring out if the element is dirty or pristine, as form.value[key] only returns a string array, not an array of the FormControls.

I am looking for either an easier way to do what I am trying to achieve, or a way to validate the form properly.

1

There are 1 answers

1
Rahul Singh On BEST ANSWER

you can check the control status using

if touched is true then its dirty

this.form.get('controlname').touched 

and for pristine you can check like

this.form.get('controlname').pristine

UPDATE

for form array it will be something like

  let val = this.user.get('<FormArray>') as FormArray;
  console.log(val.at(index));

you can now use pristine and touched on this variable