1

I am trying to set the input type number's default (initial) value as 1 but is having a difficult time figuring out how to do it. I know that I can set the value with value="1" if there is no formControlName. I tried inputNum: new FormControl(1, [Validators.required, Validators.pattern('^[1-9]\\d*$')])

and

inputNum: new FormControl([1, Validators.required, Validators.pattern('^[1-9]\\d*$')]) without success.

The input should have the initial value of 1 but I should be able to set it as 1 to whatever positive whole number.

 <input formControlName="inputNum" class="form-control" [ngClass]="{'is-invalid':inputNumForm.touched && inputNumForm.errors}" type="number">
    <div class="invalid-feedback" *ngIf="inputNumForm.touched && inputNumForm.errors">
       <label *ngIf="inputNumForm.errors.required">Numbers Only</label>
    </div>
  public form = new FormGroup({
    inputNum: new FormControl('', [Validators.required, Validators.pattern('^[1-9]\\d*$')]),
  });

  get inputNumForm(): FormControl {
    return this.form.controls['inputNum'] as FormControl;
  }

5
  • 1
    this.form.setValue(YOUR_VALUE) or you can do it directly on the element as there is a value property, check: angular.io/api/forms/AbstractControl#setValue Commented Jul 18, 2019 at 9:08
  • @Bargros I totally over complicated the problem and missed this. Thank you. Commented Jul 18, 2019 at 9:13
  • 1
    no problem, an upvote then? XD Commented Jul 18, 2019 at 9:37
  • I think you forget to add formGroup directive 🤔 Commented Jul 18, 2019 at 10:02
  • @user9553525 check this demo stackblitz.com/edit/angular-p9lgax Commented Jul 18, 2019 at 10:03

2 Answers 2

1
 public form = new FormGroup({
    inputNum: new FormControl('1', [Validators.required, Validators.pattern('^[1-9]\\d*$')]),
 });
Sign up to request clarification or add additional context in comments.

Comments

0

Here is the Working Example check out

<input text validateDecimalOnType='false' id='numeric' value='1'  /> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.