Leonard Loss
Leonard Loss

Reputation: 69

How to set default form Value from Observable?

Here is my ts component

export interface Product{
    id?:string,
    name:string,
    price:string;
    quantity:string;
    tags:Tags[];
    description:string;
    files: File[];
}

product$:Observable<Product | undefined>;

ngOnInit(): void { 
  this.store.dispatch(new productActions.LoadProduct(fromProduct.getCurrentProductId.toString()));
  this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
}

Last and the second statements gather the value of product observable and work fine.

this.product = this.fb.group({
    name:['',[
      Validators.required,
      Validators.minLength(1),
      Validators.maxLength(128)
    ]],
    price:['',
    Validators.required],
    tags:this.fb.array(this.tags),
    quantity:['',Validators.required],
    description:['',
    Validators.required]
  });
}

Now what I want is to set the default value of Form from Product$ (observable)

The above code sets the default value of name ''. But I want to set a default value from (product$ | async).name----->> this works fine in Html, but I have no idea how to do it in typescript.

Thanks for helping me.

Upvotes: 2

Views: 2629

Answers (2)

maiksch
maiksch

Reputation: 189

You could put your whole FormGroup initialization into a subscribe. Don't forget to use the first operator though, since you only want to do this once and then unsubscribe.

this.product$
    .pipe(first())
    .subscribe(product => {
        this.product = this.fb.group({
            name:[product.name,[
              Validators.required,
              Validators.minLength(1),
              Validators.maxLength(128)
            ]],
            price:['',
            Validators.required],
            tags:this.fb.array(this.tags),
            quantity:['',Validators.required],
            description:['',
            Validators.required]
          });
        }
    });

Upvotes: 3

Kunal Karmakar
Kunal Karmakar

Reputation: 581

You need to subscribe to the observable so that when there is a value passed, you are able to receive it and do something using it. Probably something like this:

this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
this.product$.subscribe(valueFromSubscription => this.product.patchValue(...));

Upvotes: 3

Related Questions