How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

   <tr *ngFor="let row of categories ">
    <td>{{row.categoryName}}</td>

    <td>{{row.visible}}</td>
    <td>{{row.instanceNumber}}</td>
    <td> <a class="btn btn-info btn-fill " [routerLink]="['/control/category']">Modify</a>
    </td>

When attempting to send the row/category object along with the routing, I find myself redirected to an empty form. My goal is to map the current row data to the original form so that I can modify only specific fields rather than all.

In my Angular application, I utilize formbuilder!

ngOnInit() {
    this.relationForm = this.fb.group({
      relationName: ['', [Validators.required, Validators.minLength(3), Validators.pattern('[a-z]+([A-Z][a-z]*)*')  ]],
      humanFormat: ['', [Validators.required, Validators.minLength(3)]],
      populate: ['', [Validators.required, Validators.pattern('TRUE|FALSE')]],
      visible: ['', [Validators.required, Validators.pattern('TRUE|FALSE')]],
      generalizations: ['', [Validators.required, Validators.minLength(3),Validators.pattern('[a-z]+([A-Z][a-z]*)*') ]],

I understand that I need to use something like this, but the where and how remain a bit unclear!

 this.productForm.patchValue({
            productName: this.product.productName,
            productCode: this.product.productCode,
            starRating: this.product.starRating,
            description: this.product.description
        });
        this.productForm.setControl('tags', this.fb.array(this.product.tags || []));

Answer №1

If you want to enhance your code, consider the following example. As you loop through your data, implement a click event to handle the selected item:

<div *ngFor="let relation of relations">
 {{relation.categoryName}} 
 <button (click)="modify(relation)">Modify</button>
</div>

Upon clicking, ensure that the chosen item is stored in a service before navigation, allowing easy retrieval afterwards:

modify(relation) {
  this.service.addRelation(relation);
  this.router.navigate(['your path here'])
}

Remember, make sure to inject Router into the constructor for effective usage: private router: Router.

To learn more about services, refer to the detailed explanation in the official documentation. When using an observable, opt for a BehaviorSubject over a Subject as it emits without requiring next(), as explained in this Answer.

Service setup:

private relation = new BehaviorSubject<Object>({})

relation$ = this.relation.asObservable()

addRelation(relation) {
  this.relation.next(relation)
}

In another component with a form, subscribe to the service's observable to populate your form based on the received values:

constructor(private service: RelationService, private fb: FormBuilder) {
  service.relation$.subscribe(relation => {
    this.relation = relation;
    this.buildForm();
  });
}

Fill your form fields with the object's values received from the service:

buildForm() {
  this.relationForm = this.fb.group({
    categoryName: [this.relation.categoryName],
    author: [this.relation.author]
  });
}

This example serves as a foundation for customization and implementation into your own project!

Feel free to explore this interactive DEMO.

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

Single array returned by observable

Issue: I am looking for a way to consolidate the multiple arrays returned individually into a single array. Solution: fetchAllRiders() { var distanceObs = Observable.create(observer => { this.http.get(this.API + '/driver/all').map(res = ...

Is there a faster way to sort this data with Javascript (or JQuery for extra speed)?

Recently, I've encountered a challenge with sorting an HTML table using JavaScript. The table can potentially contain over a thousand rows. This is what my current setup looks like in terms of HTML: <div id="mycollection" class="table"> &l ...

I. Discovering the Step-by-Step Guide on Retrieving User Information from Facebook Upon Generating App

I have set up a Facebook login for user registration on my website. However, I am only able to retrieve the profile name and user ID from Facebook. How can I access the email and other user information? Here is the data I am currently receiving from Faceb ...

Discover the perfect method for combining two objects while updating any empty values with a new specified value. Furthermore, in the case where the new value is also

My task involves working with an array of objects where each time I select a value, it gets pushed into the array. My goal is to merge two objects that share the same key "code" and remove any empty values. (4) [{…}, {…}, {…}, {…}] 0: {code: "abc ...

Unable to trigger dispatchEvent on an input element for the Tab key in Angular 5

In my pursuit of a solution to move from one input to another on the press of the Enter key, I came across various posts suggesting custom directives. However, I prefer a solution that works without having to implement a directive on every component. My a ...

Tips for correctly passing the type of combineReducers: I encountered an error saying "Property '...' does not exist on type 'Reducer<CombinedState{}>"

I am currently integrating TypeScript into my react/redux project. Unfortunately, I am encountering an error that is preventing my app from loading. The issue is shown in the screenshot below: https://i.sstatic.net/HkPwo.png Within my index.tsx file, I a ...

Looking to update properties for elements within the Angular Material 16 mat-menu across the board?

Currently working with Angular Material 16 and I have a question regarding the height of buttons inside the mat-menu element. Here is an example of the code: <button mat-icon-button> <mat-icon>more_vert</mat-icon> </button> ...

Setting up a personalized configuration entry in environment.js

I am currently working with EmberJS version 2.4.2 and I have a specific requirement to handle custom configuration entries using an environment.js file. var ENV = { APP: { myKey: "defaultValue" } }; While everything works perfectly in development ...

How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry. var data = { rooms: ...

How to choose the option in one select box based on the selection in another, and vice versa

How can I dynamically select options in one select box based on the selection of another, and vice versa? I am using Ajax to redirect to a query page. while($result = mysql_fetch_assoc($query1)) { echo "<option value=".$result['username' ...

Encountering a 404 error when trying to reload the page?

My React Router is functioning properly in the development environment. Here's what I implemented in Webpack Dev Server: historyApiFallback: { index: 'index.html', } Now, when transitioning to production mode, I wanted to replicate the ...

adjust time in jQuery AJAX request when a button is clicked

I have the following code snippet that triggers when a button is clicked. When a user clicks on a button, I want to show a progress bar or waiting image in the browser for 5 seconds. How can I set a timeout and display the progress bar or waiting image wh ...

Creating a messaging platform

I'm trying to figure out the best approach for developing a chat application that can handle thousands of users. I'm unsure about how to efficiently ping the server using AJAX at intervals of every second or less, and then check for any new reco ...

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

Get your hands on a complimentary Angular 2 scheduling tool

I am in need of integrating a scheduler into my angular 2 application. My goal is to schedule various employees within a day view and I found two paid components that might work for me: FullCalendar Scheduler Demo Bryntum Angular 2 Scheduler Currently, ...

What is the best technique for creating a preloader that can seamlessly fill the background of a vector image?

I am looking for guidance on creating a CSS3 preloader using a vector image. My goal is to have the logo start off transparent with only the border visible, and as the loading occurs, fill in from bottom to top with the background color. Thank you to ever ...

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...

What is the best method to reset the chosen option in a dynamic select dropdown using React?

I have a form set up with a Select dropdown that is populated dynamically from the server. The issue I'm facing is that after selecting an option from the dropdown and then saving or canceling the form, the selected value remains in the field when I ...

After updating to Angular 9, the ViewChild functionality seems to be malfunctioning

Is there a change in ViewChild behavior? Since upgrading to Angular 9, the MatSideNav menu has ceased to function. export class SidenavOpenCloseExample implements OnInit, AfterViewInit { @ViewChild('menuSide', {read: MatSidenav, static: true} ...

Could JSON be the solution for combining a number and a string in a single key-value pair?

I am working on defining a nested JSON object that will store a key value pair with an integer (representing the amount of something) in use case 1, and a key value pair with a string (UUID) in use case 2. The ultimate goal is to analyze this data in futu ...