How can you establish the default value for a form from an Observable?

Check out my TypeScript component below

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));
}

The last two statements retrieve the value of the product observable and function properly.

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]
  });
}

My current aim is to set the default Form values from Product$ (observable)

In the above code, the default value for name is set to ''. However, I would like to set a default value from (product$ | async).name----->> This functionality works correctly in HTML, but I am unsure how to implement it in TypeScript.

Thank you for your assistance.

Answer №1

To ensure your FormGroup initialization is executed only once and then unsubscribed, consider placing it within a subscribe function. Remember to include the first operator in order to achieve this.

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]
          });
        }
    });

Answer №2

To ensure you can access any passed values, it is important to subscribe to the observable. Here's an example of how you can achieve this:

const data$ = this.dataService.getDataObservable();
data$.subscribe(data => {
  // Do something with the received data
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The sanitizer variable becomes null when accessed outside of the NgOnInit function in Angular using TypeScript

At first, I added DomSanitizer to the component: import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser'; Next, a class was created and included in the constructor: export class BlocklyComponent implements OnInit { primar ...

Guide to making a Material Design Radial effect animation

I am looking to create a unique toolbar effect by following the material design radial reaction choreography guideline. https://i.stack.imgur.com/6oB8r.gif I want to achieve this using an angular 2 transition, but I need some guidance on how to implement ...

The Vue property I customized in my component is not being recognized by VSCode(Vetur)

I've successfully implemented a plugin in Vue by declaring it in a main.ts file, defining its type in a plugin.d.ts file, and utilizing it in a component.vue file. Although the compilation is error-free, I am encountering an issue with VSCode intellis ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Resolving circular dependencies caused by APP_INITIALIZER

My AuthenticationService is responsible for loading the AngularFirestore and is loaded in the RootComponent. All app modules are lazily loaded within the RootComponent (which contains the main router-outlet). However, several sub-modules also load the Ang ...

angular-oauth2-oidc - Issue with missing 'State' and 'Scope' parameters

One crucial requirement set by the identity server is to refrain from including 'state' and 'scope' in the URL. The specified request format is as follows URL?app=xxx&response_type=code&client_id=yyy&state=zzz&redirect_ ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

Unable to bring in the directive from the Angular library

I've created this custom Directive within my library: @Directive({ selector: '[layoutHeaderTitle]', standalone: true }) export class HeaderDirective { constructor( readonly tpl: TemplateRef<any>, private re ...

React Typescript is causing issues with the paths not functioning properly

Looking to simplify my import paths and remove the need for deeply nested paths. Currently working with React and TypeScript, I made adjustments to my tsConfig file like so: { "compilerOptions": { "baseUrl": "src", & ...

Discovering the precise query parameters from a URL within an Angular application

I came across a Stack Overflow post about obtaining query params. However, I noticed that one of my query params contains "%2" which converts to a "+" when displayed in my Angular code. Additionally, my param2 does not store the complete value "testingsome ...

Creating conditional keys using the Zod library based on the value of another key

Incorporating the TMDB API into my project, I am making an effort to enhance type safety by reinforcing some of the TypeScript concepts I am learning. To achieve this, I am utilizing Zod to define the structure of the data returned by the API. Upon invest ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

Angular 2 partial static routing parameters with customizable features

Can an angular 2 routing configuration include a partial-static parameter? Currently, I am using a classic parameter setup like this: const routes: Routes = [ { path: ':type/fine.html', pathMatch: 'full', redirectTo: &ap ...

Explain the object type that is returned when a function accepts either an array of object keys or an object filled with string values

I've written a function called getParameters that can take either an array of parameter names or an object as input. The purpose of this function is to fetch parameter values based on the provided parameter names and return them in a key-value object ...

Each time the Angular Service is called, it undergoes a reset process

For my Angular web project, I have implemented an AuthenticationGuard and an AuthenticationService to manage security. These components are from a separate branch of the project that is functioning perfectly. This is how the process should occur: Go to ...

Adding a new element to the div by referencing its class name

One way to add a component to the view is by using ViewContainerRef. For instance, HTML File: <div #Ref>it is possible to append the component here</div> TS File: @ViewChild("Ref", { read: ViewContainerRef }) public Ref: ViewContainerRe ...

Creating dynamic elements in Angular2 componentsIn Angular2, you can seamlessly

Utilizing the Google Maps JavaScript API in my project, I faced the challenge of displaying an Angular component within an InfoWindow. After loading the Google Maps API with the Jsonp service, I had access to the google.maps.Map object. In a component, I ...

Guide to utilizing props conditionally in a Material UI TextField component

I am looking to build a comprehensive component using Material UI TextField along with Formik While I have managed all other props, I am facing difficulty in dealing with value and onChange, I have tried using 2 functions for onChange, but find it cumber ...

NgOnChanges replaces form control value when user inputs text

In my autocomplete form control component: @Component({ selector: 'app-autocomplete', templateUrl: './app-autocomplete.view.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class AutoCompleteFilterComponent ...