BBacon
BBacon

Reputation: 2678

Observable .startWith not working

'html'

<input type="number" placeholder="{{'Quantity' | translate}}" min="1" max="30" matInput formControlName="quantityControl" (change)="quantityChanged()"/>

'controller.ts'

this.inquiryForm = this.formBuilder.group({
      'quantityControl': new FormControl(1, [Validators.min(1), Validators.max(30)])
    });

this.inquiryForm.get('quantityControl').valueChanges.pipe(
          startWith(1),
          map(quantity => this.currentQuantity = (quantity > 0 ? quantity : 1))
        ).startWith(1);

Neither the startWith from 'rxjs/operators/startWith' nor the Observable one, and not even the value set at FormControl/FormGroup instancing works. Form value always null after ngOnInit. Any ideas why?

Upvotes: 1

Views: 2223

Answers (1)

Pierre Mallet
Pierre Mallet

Reputation: 7221

If I understand correctly your need, you want to ensure quantity always > 0.

Here is a stackblitz based upon your code.

the changes are here :

this.inquiryForm.get('quantityControl').valueChanges.pipe( // 1 
  filter(quantity => quantity < 1) // 2 
).subscribe(value => {
  this.inquiryForm.get('quantityControl').setValue(1); // 3
});

To achieve your logic

1/ we subscribe to the valueChange operator (like Ingo Bûrk noticed)

2/ we filter to keep only value < 0 (because we cant to take action only on those value)

3/ Then every time the value is emitted ( so < 0 ) we just reset the formControl value to 1.

Regarding your initial value error, I have no clue, it works like a charm for me.

Upvotes: 1

Related Questions