Using Angular 8, remember to not only create a model but also to properly set it

hello

Here is a sample of the model I am working with:

export interface SiteSetting {
    postSetting: PostSetting;
}

export interface PostSetting {
    showDataRecordAfterSomeDay: number;
}

I am trying to populate this model in a component and set it as the form value.

   postSettingAddFormGroup: FormGroup;
  postSettingModel: SiteSetting;

  constructor(private formBuilder: FormBuilder, private postsettingService: PostService, private alertService: AlertService, private route: Router) {
    this.postSettingModel = {} as SiteSetting;
    this.cachedSetting();
  }

  ngOnInit(): void {
    this.initializeForm();
  }


  ngAfterViewInit(): void {
  }


  initializeForm(): void {
    this.postSettingAddFormGroup = this.formBuilder.group({
      showDataRecordAfterSomeDay: ['', Validators.compose([Validators.required, Validators.minLength(0), Validators.maxLength(365)])]
    });
  }

  cachedSetting(): void {
    this.postsettingService.getPostSetting().subscribe(data => {
      this.postSettingModel.postSettingsModel = data
    })
  }

I have implemented this code but encountered an issue with postSettingModel.

What could be causing this problem? How can I troubleshoot this model?

Answer №1

It seems like the issue lies in not properly connecting your form with the fetched data. Consider implementing the following solution:

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  postSettingAddFormGroup: FormGroup;

  constructor(private formBuilder: FormBuilder, private postSettingService: BtwService) {
    this.postSettingAddFormGroup = this.formBuilder.group({
      showDataRecordAfterSomeDay: new FormControl(null, Validators.compose([Validators.required, Validators.minLength(0), Validators.maxLength(365)]))
    });
  }

  ngOnInit() {
    this.postSettingService.getPostSetting().subscribe(data => {
      this.postSettingAddFormGroup.patchValue({
        showDataRecordAfterSomeDay: data.showDataRecordAfterSomeDay
      });
    });
  }
}

Make sure to create your form within the constructor.

The "showDataRecordAfterSomeDay" is a number, so initialize it as null or 0, instead of ''.

To update your form with the fetched data, utilize "PatchValue" as shown in the ngOnInit function.

In your HTML file:

<form [formGroup]="postSettingAddFormGroup">
  <input type="text" formControlName="showDataRecordAfterSomeDay">
</form>

If the PostSettingService returns a PostSetting object, then ensure your method looks like this:

getPostSetting(): Observable<PostSetting> {
    return of({showDataRecordAfterSomeDay: 10});
}

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

Hide the dropdown menu when the user clicks anywhere else on the screen

I have a scenario with 2 dropdown buttons. When I click outside the dropdown or on it, it closes. However, if I click on the other dropdown button, it does not close and the other one opens. I want them to close when I click on the other button or anywhere ...

submitting a form including a file through ajax communication

For the past two weeks, I've been trying to find a solution to my unique problem. I've created a custom form that I need to upload along with one or more files. Our backend is running ruby on Rails, and the data must be formatted into a specific ...

Comparing jQuery's min-width and width properties: A guide on eliminating pixels

Exploring some basic jQuery and JavaScript here. When I use the .width() method, I get an integer value. However, when I use .css('min-width'), it returns a value in pixels which makes it challenging to perform calculations. What would be the be ...

The 'Image' component does not have a propType defined for the native prop 'RCTImageView.overlayColor' with a native type of 'number'

Greetings, I am encountering an issue while attempting to run my react native application on Android. The app has been functioning flawlessly on iOS for several months, but this is our first endeavor at utilizing it on Android. We are using react-native .1 ...

What is the process for linking to a backend on a distinct port in Next.js?

I am working on a project with Next.js and I am facing a challenge in connecting to a backend server that is running on a different port. The frontend of my application is on port 3000, while the backend is on port 8000. My goal is to interact with the bac ...

How to convert DateTime format from database to input type='datetime' using PHP

I am having trouble retrieving a column from the database of type datetime and passing it to an input box with the type 'datetime' in my form. Unfortunately, nothing is being passed. <input type="datetime-local" id="myDate"> <button id= ...

Initial Search Function in a MEAN Stack Site

Working on a MEAN stack application for a school project, I'm almost done but struggling to add search functionality. Creating a search feature for ICD-10 codes in a medical app is my goal. Just need a basic search of symptoms or codes that displays ...

Having trouble storing data accurately in local storage using React

I implemented a combination of useContext and useEffect to store useContext data in local storage, but I am facing challenges due to conditional rendering. The scenario involves displaying a sign-in button when the user is not logged in and a log-out butto ...

Rotate a sphere in three.js in order to align the mapped image of the globe with the GeoJSON data that is displayed in the same three

I have successfully implemented a globe in three.js with an image mapped onto the sphere. Furthermore, I am utilizing the ThreeGeoJSON library to visualize geojson data on top of the globe. However, the geographies from the geojson data do not align corr ...

Prepared SQL Statement in NodeJS for MSSQL using WHERE IN clause

I'm using the sql npm package in my Node.js project. Currently, I have an array of product SKUs like this: var skus = ['product1', 'product2', 'product3']; The SQL query stored in a file looks like this: SELECT * FROM ...

Implementing a feature in React where the active class is applied only to the next element upon clicking

I'm just starting out with React and working on a custom menu bar project. The Mobile menu includes 2 dropdown submenus, which I want to toggle open and close by clicking an arrow. Currently, the arrows are functioning, but when I click on one arrow, ...

Setting up ReactJS and TypeScript in a fresh MVC5 project from scratch

After extensively trying out various tutorials, I have yet to successfully run a basic MVC5 project using TypeScript and ReactJS. For reference, I have created these projects from scratch in Visual Studio 2015 with .NET 4.6.1, using the ASP.NET Web Applic ...

Why does the 401 error continue to persist while attempting to log in using Google Identity service on my Laravel application?

Trying to implement Google authentication services for user authentication. I've already integrated Laravel sanctum to allow users to log in and register successfully. This time, I want to add Google Identity services as an additional authentication ...

Displaying a component after retrieving a value from AsyncStorage in a React Native application

I have developed a React Component that saves user settings in the AsyncStorage and retrieves them upon loading. The functionality of storing and retrieving data is working fine, but I am facing an issue where the component renders before the values are ...

My goal is to develop a custom forEach function that retrieves a substring from each element in an array

I have a file containing image names like: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png In my JavaScript document, I am trying to read this file and convert it into an array. Then, I w ...

Avoid triggering the API with rapid successive clicks

My project involves creating an Instagram-clone with like and dislike buttons. When a user is logged in and hasn't liked or disliked a post yet, both buttons appear as black. If the user likes a post, the like button turns blue, and if they click disl ...

Using Vue to showcase the result of a form submission on a separate page

Working with a <form> in the context of vue has been successful as I am able to send the form data to the server, receive a JSON response, and print it on the console. However, my current challenge involves displaying this JSON response on a differe ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

[attr.disabled]="isChecked ? '' : 'disabled'"

[attr.disabled]="isChecked == true ? '' : disabled" Can anyone assist me with disabling unchecked checkboxes in a loop using Angular 8? [attr.disabled]="isChecked == true ? '' : disabled". Need help with this in Ang ...