1
votes

The problem here is supposed to be simple but I'm not able to initialize an input field for a reactive form and have that control as valid.

lets say I have this code:

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
  profileForm = this.fb.group({
    firstName: string,
    lastName: string,

    address: this.fb.group({
      fName: ['initial value', [Validators.required]],
      city: ['', [Validators.required]],
      state: [''],
      zip: ['']
    }),
  });

  constructor(private fb: FormBuilder) { }
}

And in the template I have lets say:

<input [(ngModel)]="firstName" formControlName="fName" />

The problem is that setting the default value this way is not working:

fName: ['initial value', [Validators.required]],

second way not working:

fName: new FormControl('initial value', [Validators.required])

third way is in the template doing this is not working as well:

 <div>
    <input [(ngModel)]="firstName" formControlName="fName" [value]="'default value'"/>
 </div>

A fourth way to do it is:

this.address.controls['fName'].setvalue('default value');
this.address.controls['fName'].updateValueAndValidity();

So when I try all these combination or one of them at a time, and go in the debugger and verify what is the value of: this.address.controls['fName'].value it gives me an empty value --> ''

as a result even if in my form the field is initially populated and I have to provide the others fields then because of this field my form is not valid I then it's not showing my save button as enabled.

can some one explain why this behavior or explain what is the right way to go with this ?

Note: I'm just giving here a small code example as a hint, because my real code is part of a bigger and a proprietary angular 6 application.

I've to clean up this example but here is one using: <input type="text" class="form-control" id="username" formControlName = "username" [(ngModel)]="name">

https://stackblitz.com/edit/angular-reactive-forms-jhg6ds?file=app%2Fapp.component.ts

(will update this example later.)

In this case, the default value is not shown, because I think kind of a concurrency with ngModel content, so I want to set that default value event if the content of ngModel is empty (example when creating a empty form, the user has to find some field already filled (and then valid))

1
You would be getting a warning for using formControlName and [(ngModel)] on the same element. That's kind of redundant and Angular has depricated it in V6. Angular will get rid of it in V7SiddAjmera
@SiddAjmera : I already know that, currently I'm getting these warnings but will remove this when migrating to angular 7 in October, or will remove this in an upcoming Jira.HDJEMAI
Why not just use the first approach without [(ngModel)] in your template: <input formControlName="fName" />SiddAjmera
Well there is a number of complications related to selecting default values for different element, like select, checkboxes, … but will try that later now I'm trying to find a solution with this ngModel since it's in code now. with ngModel it's very easy for a number of thing instead of going completely the reactive way by using for example the valueChanges method witch don't help with the initial value as I experimented.HDJEMAI
Why don't you make an interactive example?Bennett Hardwick

1 Answers

1
votes

Edited version: https://stackblitz.com/edit/angular-reactive-forms-atvaym

template:

<form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <label for="username">UserName</label>
        <input type="text" class="form-control" id="username" formControlName="username">
        <span class="help-block" *ngIf="!SignupForm.controls.username.valid && SignupForm['controls'].username.touched">
   <span *ngIf="SignupForm['controls'].username.hasError('nameIsForbidden')">name is invalid</span>
        <span *ngIf="SignupForm['controls'].username.hasError('required')">field is required</span>
        </span>
    </div>

    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" id="email" formControlName="email">
        <span class="help-block" *ngIf="!SignupForm.controls.email.valid && SignupForm['controls'].email.touched">
   <span *ngIf="SignupForm['controls'].email.hasError('emailIsForbidden')">name is invalid</span>
        <span *ngIf="SignupForm['controls'].email.hasError('required')">field is required</span>
        </span>
    </div>

    <div class="radio" *ngFor="let gender of genders">
        <label>
<input type="radio" [value]="gender" formControlName = "gender">{{gender}}
</label>
    </div>

    <div formArrayName="hobbies">
        <h4>Hobbies</h4>
        <button class="btn btn-default" type="button" (click)="onAddHobby()">Add Hobby</button>
        <div class="form-group" *ngFor="let hobbyControl of SignupForm['controls'].hobbies['controls']; let i=index">
            <div [formGroupName]="i">
                <div [formGroup]="SignupForm['controls'].hobbies['controls'][i]">
                    <input type="text" class="form-control" formControlName="name">
                </div>
            </div>
        </div>
    </div>
    <span class="help-block" *ngIf="!SignupForm.valid && SignupForm.touched">please enter valid data</span>
    <button class="btn btn-primary" type="submit">Submit</button>
</form>

Typescript:

  ngOnInit(){
    this.SignupForm = this.fb.group({
      username: [{value: 'default name', disabled: false}, [Validators.required, this.validateName()]],
      email: [{value: 'default name', disabled: false}, [Validators.required, Validators.email, this.validateEmail()]],
      gender: [{value: 'female', disabled: false}, [Validators.required]],
      hobbies: this.fb.array([])
    });
  }

  onAddHobby(){
    const controls = <FormArray>this.SignupForm.controls['hobbies'];
    let control = this.fb.group({
      name: [{value: 'hobbi', disabled: false}]
    });
    
    controls.push(control);
  }

  private validateName(): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      for(let i of this.forbiddenUserNames){
        if(i === control.value){
          return {'nameIsForbidden': true};
        } else {
          return null;
        }
      }
    }
  }
    
  private validateEmail(): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      if(control.value === '[email protected]'){
        return {'emailIsForbidden': true};
      } else {
        return null;
      }
    }
  }

And I recommend to look at this article about Async Validators https://alligator.io/angular/async-validators/