Durham Smith
Durham Smith

Reputation: 157

Angular2 FormBuilder default values no longer available when using ngModel

I have noticed that when using [(ngModel)] I am no longer able to take advantage of the default values provided by FormBuilder.

Currently I have the following in my form

<form (ngSubmit)="submitFees()" [ngFormModel]="FeeForm">
    <div class="form-group row">
      <div class="col-sm-12">
        <input type="number" id="Fees" class="form-control"
        placeholder="Fee" required
       [ngFormControl]="FeeForm.controls['ContentFee']"
        [(ngModel)]="Fee">
      </div>
     Fee: {{postFee*1.2| number:'1.2-2'}}
  </div>
</form>

and in my constructor:

constructor(){
    let fb = new FormBuilder();
    this.FeeForm = fb.group({
        ContentFee: ['0', Validators.required]
    });
}

This gives me a NaN for {{postFee}} and when I submit the form and console.log(FeeForm.value) I get ContentFee:undefined. however if I remove [(ngModel)] all works as expected.

How would I be able to still make use of default values with [(ngModel)]?

Upvotes: 2

Views: 424

Answers (1)

Durham Smith
Durham Smith

Reputation: 157

From my other question it seems that what is needed is to include the initialisation for the in the constructor like this:

constructor(){
    this.Fee = 0 // This will show up as the default value 
    let fb = new FormBuilder();
    this.FeeForm = fb.group({
        ContentFee: ['0', Validators.required] // Value not used
    });
}

Upvotes: 1

Related Questions