Implementing bidirectional data binding individually within Angular

My custom table component requires a model for row selection actions that can be two-way bound in the following way:

<my-table [(selected)]="selectedRows"></my-table>

Alternatively, I have the option to pass an item through one-way data binding if I do not need to track changes made to that model:

<my-table [selected]="selectedRows"></my-table>

If I prefer not to bind the data item two-ways and instead want to pass it down via one-way data binding along with a handler/event emitter, the syntax would look something like this:

<my-table [selected]="selectedRows" (selected)="handleSelectedChanged($event)"></my-table>

Is it possible to achieve this functionality with minimal or no changes to the my-table component? Or do I need to create an @Output parameter on the my-table component in order to utilize handleSelectedChanged($event)?

Thank you!

Answer №1

No need to make any changes within the my-table component table. Just remember, when you want a custom event to be emitted, use (selectedChange) instead of (selected). That's all there is to it. Make sure you have already set up the Input binding for selected and the Output binding for selectedChange somewhere within the my-table component. Keep in mind that using selected change property binding is optional.

<my-table 
  [selected]="selectedRows" 
  (selectedChange)="handleSelectedChanged($event)">
</my-table>

If you're curious about why two-way binding requires the Change suffix on the event, it's because of the design. For a clearer understanding, take a look at Angular's ngModel directive as well.

<input [ngModel]="myModel" (ngModelChange)="myModel = $event" />
// You can also handle assignment by calling a function
<input [ngModel]="myModel" (ngModelChange)="inpuChanged($event)" />

This code snippet can also be written as

<input [(ngModel)]="myModel" />

Answer №2

parent.component.html

<my-table [selected2]="selectedRows" (selected)="handleSelectedChanged($event)"></my-table>

parent.component.ts

handleSelectedChanged(event){
    // console.log(event)
      this.selectedRows = event
    }

my-table.component.ts

@Input() selected2: any;
@Output() selected: EventEmitter<any> = new EventEmitter();

OnCLCICK(){
 this.selected.emit({'key':'value'})
}

or :--

user.service.ts

@Output() selected: EventEmitter<any> = new EventEmitter();

 setselected(data) {
 this.selected.emit(data);
}

getselected() {
        return this.selected;
      }

my-table.component.ts

@Input() selected2: any;

constructor(
public user: Userservice
){
}

 onclick(){
this.user.setselected({'key','val'})
}

parent.component.html

<my-table [selected2]="selectedRows"></my-table>

parent.componnet.ts

    constructor(
    public user: Userservice
    ){
    }

ngOnInit(){
this.userService.getselected().subscribe((data) => {
      this.getData(data);
    });
}

getData(data){
console.log(data)
}

Answer №3

Your my-table.component.ts already has an implementation of both @Input() and @Output() using selected and selectedChange().

For custom two-way data binding in Angular, the event emitter and variable should be defined as follows:

@Input() date: Date;

@Output() dateChange: EventEmitter<Date> = new EventEmitter<Date>();

By using [(date)], a two-way data binding is created.

If you prefer not to use two-way data binding, you can omit the () in [(date)] and simply use

[date]</code; it will function as normal parent-child component communication.</p>

<p>To listen for changes and perform actions based on the value of <code>date
, use the (dateChange) event emitter and bind it to a function to monitor changes.

In response to your question about creating a new @Output() in

my-table.component.ts</code, there is no need to create or add any additional event emitters. The functionality is already implemented through <code>selectedChange()
. Simply include:

<my-table [selected]="selectedRows" (selectedChange)='handleSelectedChanged($event)'></my-table>

Now, with selectedRows as input and selectedChange as output emitting an event whenever there are changes in selected, the event will be passed through handleSelectedChanged().

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

Is there a way to change the names of bundles created during ng serve in Angular 13?

I am looking to change the names of bundles created after running ng serve in an Angular Application. Currently, the bundles are: vendor.js polyfills.js styles.css styles.js main.js runtime.js I want to rename these ...

What are the steps to verify a query's accuracy and effectively manage any errors that may arise

When using my API, the endpoint '/api/students' will display all student names. If a req.query is input with a specific name, such as "John", the endpoint becomes '/api/students?name=John'. I have implemented regex to ensure that only c ...

Troubleshooting issues with debouncing a Redux dispatch and encountering unexpected results

I've been attempting to implement debounce for an API action that involves a dispatch call to a reducer. The goal is for the API call in the browser to debounce after a specific delay, but instead, it's resulting in multiple API calls after the d ...

The jQuery function creating an object that calls itself as a method

Currently, I am in the process of developing a Jquery game for my school project. In order to make the create() function recall itself, I have included a setTimeout() at the end of the method. However, it seems that the function is only running once when ...

Can a Typescript type alias be altered in real time?

Currently, I am developing an Angular library that will function as an API client. The challenge I am facing is that some of the applications utilizing this library are configured with an HttpInterceptor to automatically transform date strings into JavaScr ...

Emphasizes the P tag by incorporating forward and backward navigation options

My goal is to enable users to navigate up and down a list by pressing the up and down arrow keys. For example, if "roma" is currently highlighted, I want it to change to "milan" when the user presses the down arrow key. Here is the HTML code I am working w ...

Combining Elasticsearch with AngularJS or Node.js

I am currently developing a MEAN stack application that utilizes elasticsearch for searching records. In my AngularJS controller, I have implemented the following code to interact with the elasticsearch server: instantResult: function(term) { var client = ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

Exploring Angular 7's Child Routes

Currently, I am facing an issue with cleanly separating Routes based on Forms and Menus. For instance, I have a Menu Item named Setup which contains sub Items called Bucket and Tags. Both Bucket and Tags are utilized throughout the application to categoriz ...

What is the best way to include the existing query string value in the hyperlinks on my page?

My main coding objective is to simultaneously search multiple websites. To accomplish this, I want to create a query string containing the search terms (primarily for analytics purposes) using a form. By utilizing JavaScript, I am aiming to include the s ...

I am having trouble getting Mongoose to perform operations on my data

After running the code and initiating the trade offer (receiving item, fetching data, then taking action with my app), I encounter an error. emitter.on('depositImportedToDb', function(createNewDeposit) { var roundCode; var roundItems; ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

Fixes the React bug that removes only the last item in a list

I've been encountering an issue with my list of generated items. Whenever I attempt to remove one using the handleDelete callback onClick function, it always ends up removing the last item instead. Even though I added keys to each item, the removal pr ...

Is it appropriate to incorporate existing cshtml markup from MVC into Angular 6?

I am currently working on a project that involves migrating an MVC application to Angular6. The designs for this project are already created in cshtml files, which are essentially views. My question is, would it be acceptable to use these existing designs ...

Converting Angular App's local storage from synchronous to asynchronous with Indexed-db

I am utilizing local storage to retrieve data and if the data is not available in local storage, then I make a server API call, add the data to storage for future use, and return the data. This ensures that next time, the data will be retrieved from storag ...

Obtain the file path relative to the project directory from a Typescript module that has been compiled to JavaScript

My directory structure is as follows: - project |- build |- src |- index.ts |- file.txt The typescript code is compiled to the build directory and executed from there. I am seeking a dependable method to access file.txt from the compiled module without ...

JavaScript is currently only being applied to sort the first table

I am having an issue with sorting three tables on my page based on a value (year in this case). <table id="table1"> <tr> <th>Name</th> <th>Surname</th> <th>Year</th> </tr> <tr> ...

What is required to run npm rebuild node-sass --force following each instance of a `yarn add` command?

As I attempt to set up the isemail npm library, everything appears to be going smoothly. However, when I execute yarn start:dev, which essentially runs "npm run build:dev && ./scripts/gendevconfig.sh && cross-env BABEL_DISABLE_CACHE=1 NODE_ ...

Issue with ThreeJS CSG when trying to intersect extruded geometries

element, I'm facing a challenge with extracting multiple views and intersecting them to form a final polygon. The issue arises when there are floating extra parts in the result that are unexpected. My goal is to find a solution to detect these extrane ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...