@@ -2,9 +2,11 @@ import {
22 ChangeDetectionStrategy ,
33 Component ,
44 computed ,
5+ effect ,
56 input ,
7+ model ,
68} from '@angular/core' ;
7- import { toSignal } from '@angular/core/rxjs-interop' ;
9+ import { takeUntilDestroyed } from '@angular/core/rxjs-interop' ;
810import { FormControl , FormGroup , ReactiveFormsModule } from '@angular/forms' ;
911import { RouterLink } from '@angular/router' ;
1012import { products } from './products' ;
@@ -54,17 +56,27 @@ import { products } from './products';
5456 changeDetection : ChangeDetectionStrategy . OnPush ,
5557} )
5658export default class OrderComponent {
59+ quantity = model ( 1 ) ;
60+
5761 form = new FormGroup ( {
58- quantity : new FormControl ( 1 , { nonNullable : true } ) ,
62+ quantity : new FormControl ( this . quantity ( ) , { nonNullable : true } ) ,
63+ } ) ;
64+
65+ quantityEffect = effect ( ( ) => {
66+ this . form . get ( 'quantity' ) ?. setValue ( this . quantity ( ) , { emitEvent : false } ) ;
5967 } ) ;
6068
69+ sub = this . form
70+ . get ( 'quantity' )
71+ ?. valueChanges . pipe ( takeUntilDestroyed ( ) )
72+ . subscribe ( ( value ) => {
73+ this . quantity . set ( value ) ;
74+ } ) ;
75+
6176 productId = input ( '1' ) ;
6277 price = computed (
6378 ( ) => products . find ( ( p ) => p . id === this . productId ( ) ) ?. price ?? 0 ,
6479 ) ;
65- quantity = toSignal ( this . form . controls . quantity . valueChanges , {
66- initialValue : this . form . getRawValue ( ) . quantity ,
67- } ) ;
6880 totalWithoutVat = computed ( ( ) => Number ( this . price ( ) ) * this . quantity ( ) ) ;
6981 vat = computed ( ( ) => this . totalWithoutVat ( ) * 0.21 ) ;
7082 total = computed ( ( ) => this . totalWithoutVat ( ) + this . vat ( ) ) ;
0 commit comments