Transmit information from child to parent as needed using @input and @output in Angular 2

Is there a way to pass an object from child to parent without relying on @viewChild or services?

export class MultiSelectComponent implements OnInit {

selectedItems: FormSelectComponentOption[] = [];

@Input()
items: FormSelectComponentOption[];

@Output()
selected = new EventEmitter<FormSelectComponentOption[]>();
}

What method can I use to retrieve a complete FormSelectComponentOption via a "request"?

Answer №1

Instead of making a direct request, update the parent component with the selections each time they are changed.
In your MultiSelectComponent, whenever the user modifies the selections, trigger

this.selected.emit(this.selectedItems)
, then listen for these changes in the parent template using
<multi-select (select)="selectionChanged($event)" [items]="items">
. In the parent component, implement the selectionChanged() method to handle and store the updated selection.
Next time you need to retrieve data, simply refer to the saved selection in the parent component.

Answer №2

If you need to transfer data of type FormSelectComponentOption[] from a child component to its parent in response to a specific event (like click), you can achieve this using emitters.

Here is an example of how you can do it:

//Parent component html
<multi-select (selected)="itemsSelected($event)"></multi-select>

//Parent component class
public class ParentComponent {
  itemsFromChild: FormSelectComponentOption[];

  itemsSelected(FormSelectComponentOption[] items){
    this.itemsFromChild = items;
  }
}

//Child component html
<div (click)="selected.emit(selectedItems);"></div>

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

Switch statements in TypeScript may not function properly with type guards when assigning an object to a variable

I'm puzzled as to why the type guard is not working in the example provided below... Considering the following interfaces: interface ParamA { name: 'A'; aaa: boolean; } interface ParamB { name: 'B'; bbb: number; ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Resolving the problem of <Link> error in React with Typescript using react-router-dom

Currently, I am facing an issue with the 'react-router-dom' library. This is my first experience using React with Typescript; Everything was functioning properly until I introduced the from 'react-router-dom', which caused the entire ...

Upgrading Angular from Version 9 to Version 10

Currently facing an issue while attempting to upgrade Angular from version 9 to 10. Despite manually updating the package.json file as below, I am encountering this error message: "@angular/core": "^10.2.5", "@angular/common": ...

The Angular service is unable to access the Slim REST API endpoint

I have successfully configured a Slim REST API to retrieve data from the table trading_partner. <?php // Establish database connection require_once('dbconnect.php'); // Fetch all records $app->get('/path/to/trading_partner', fun ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

React: Why aren't class methods always running as expected?

I created a class component that retrieves a list of applications from an external API. It then sends a separate request for each application to check its status. The fetching of the applications works well, but there is an issue with the pinging process ...

Steer clear of encapsulating components or modifying the attributes of the encapsulating element

I am currently developing an application that involves dynamically adding components. One of the key components is a block component with the following template: <div id="{{element.id}}" class="row" [hidden]="hide"> ...

The functionality of Ionic Cordova is currently inaccessible

Currently utilizing the Ionic Native Calendar plugin in version 3.9.2 of Ionic framework. The module has been successfully installed and included in the app module. Below is the snippet where the calendar is being called: import { Component } from ' ...

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

There is no matching signature for Type when using withStyles

Struggling to convert my React App to typescript, I keep encountering the error below and cannot decipher its meaning. The app functions perfectly in plain JS. My package version is material-ui@next TS2345: Argument of type 'typeof ApplicationMenu&a ...

Give the Row ID as a parameter to a personalized component within MUI Datagrid Pro

I am currently exploring the idea of incorporating an intermediate state to row checkboxes based on the selection status of other checkboxes within a detailed panel. My approach involves crafting a custom checkbox component and implementing some logical ...

Angular CLI version incompatibility has been encountered. This particular version of CLI is specifically designed to work with Angular versions ^13.0.0 || ^13.3.0-rc.0. However, the system detected Angular version 14

After updating my ionic project to Angular 14, everything worked smoothly when running ionic s. However, when I attempted to test it on my android device by running ionic cordova run android, I encountered the following error: [ng] This version of CLI is o ...

Is there a way to dynamically alter the fill color of an SVG component using props along with tailwindcss styling?

Having a bit of trouble cracking this code puzzle. I've got a logo inside a component, but can't seem to pass the className fill options correctly. This is all happening in a NextJS environment with NextUI and tailwind css. const UserLogo = (prop ...

Ways to monitor a variable for changes and automatically update the value in related components

I feel like I may not be following best practices, so I'm hoping for some guidance. Within a provider, there is a variable that I have defined. @Injectable() export class SharedService { public mynumberservice:any=0; In both the MainComponent an ...

What is the best method for accurately capturing time-stamps from web users using Angular 2?

Is there a more accurate way to obtain timestamps in Angular 2 from my website users? Currently, I am collecting timestamps using the simple JavaScript code Date.now(), but some users may have incorrect system dates leading to inaccurate timestamps. What ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

What is the best approach for resolving this asynchronous task sequencing issue in JavaScript?

Below is a code snippet where tasks are defined as an object and the function definition should ensure the expected output is met. Let tasks = { ‘a’: { job: function(finish){ setTimeout(() => { ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

Expanding Material UI functionality across various packages within a monorepository

Currently, I am using lerna to develop multiple UI packages. In my project, I am enhancing @material-ui/styles within package a by incorporating additional palette and typography definitions. Although I have successfully integrated the new types in packag ...