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

Unable to "serialize" geoJSON information

While working with Leaflet JavaScript, I am attempting to retrieve data directly from GeoServer using an Ajax link. To display it nicely in a DataTables table, I need to convert it into JSON format as per DataTables instructions. However, I keep encounteri ...

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

Divs expanding below content in IE on a particular server

Currently, I am facing an issue with a JavaScript div that expands correctly over other content in most situations but goes under the content in one specific scenario. I am unsure about where to begin debugging this problem. To provide some context, the d ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

Utilizing two DTOs for a single controller in NestJS

I'm having trouble retrieving and transforming different types of dtos from the body. My goal is to extract and transform firstDto if it's incoming, or convert secondDto if that's what's being received. However, my current code isn&apos ...

Obtain information from the get request route in Node.js

I've been diving into nodejs and databases with the help of an online resource. As part of my learning process, I have been tasked with replicating the code below to fetch data from app.use('/server/profil'); However, I'm encountering ...

Every time a button is clicked on the interface, a new element or button will appear. This functionality is made possible through

Currently diving into a new React.js project as a beginner. I have a little challenge in the code snippet below - looking to add a button that displays "Hello World" every time it's clicked using setState. Can anyone guide me on enhancing the DisplayM ...

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...

What are the steps for implementing responsive design animation in my particular scenario?

Can someone please help me with a strange bug in Chrome? I am trying to create a responsive design for my app. The width of the 'item' element should change based on the browser's width. It works fine when the page first loads in Chrome, b ...

How do I fix TypeError: req.flash is not a valid function?

While working with user registration on a website, validation is implemented using mongoose models and an attempt is made to use Flash to display error messages in the form. However, in my Node.js app, an error is occurring: TypeError: req.flash is not ...

The conditional rendering logic in the ng-if directive does not seem to be synchronizing

Currently, I am delving into AngularJS and working on a basic application to gain familiarity with it. Within my app, there are four tabs: List, Create, Update, and Delete. However, my goal is to only display the Update and Delete tabs when I press the b ...

Switching to a different view in a React Native application

I am encountering difficulties while navigating between pages in my React Native application. Whenever I try to use the button, an error message pops up saying: TypeError: undefined is not an object (evaluating '_this.props.navigation'). My app c ...

What is the best jQuery library to add to my website?

I have included several jQuery scripts on my website for various functionalities such as sticky header, anchors, and animations. I am wondering if it is necessary to include all of them or if I can just include one or two? Here are the jQuery scripts I ha ...

Exploring Nested Data in MongoDB Aggregation using $match and $project

Struggling with crafting a Mongoose Aggregate Query to extract the permissions object of a specific member within a deeply nested structure of business data. MongoDB's documentation on this topic is lacking, making it hard for me to progress. Sample ...

Vue js is throwing an error message that says "Reading 'push' property of undefined is not possible"

I've encountered an issue while trying to navigate to other routes. The error I'm receiving is: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push') at eval (JoinRoom.vue?bd9d:74:1) This is how I pu ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...

Preserving the original "this" context while binding a callback for a React child

class Parent extends React.Component { constructor(props) { super(props) this.handleChildOnClick = this.handleChildOnClick.bind(this) } handleChildOnClick() { /* Here, I want to perform an action that involves both Child and Parent. ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. My backend systems are all set ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...