Communicating between Angular components

I'm encountering difficulties in establishing communication between two components within Angular. Despite my efforts, I can't pinpoint where I am going wrong.

Specifically, I have a table component and I aim to open a modal window (which is a separate component) displaying the details of the row clicked on within the table. While I’ve successfully set up the modal to open upon clicking, no data is being displayed.

export class TableComponent implements OnInit {
  posts: Post[];
  selected: any;

  selectRow(post) {
    this.selected = post;
    document.getElementById('modalActivator').click();
  }

  private setPosts(posts) {
    this.posts = posts;
  }

  constructor(
    private restCallService: RestCallService
  ) {}

  ngOnInit() {
    this.restCallService.getPosts().then(posts => this.setPosts(posts))
  }

}

Table HTML:

     <table>
        <tbody>
            <tr *ngFor="let post of posts;"
                (click)="selectRow(post)">

                <td>{{post.userId}}</td>
                <td>{{post.id}}</td>
                <td>{{post.title}}</td>

            </tr>
        </tbody>
    </table>

    <app-table-row-expanded> [postFromParent]="selected"</app-table-row-expanded>

The modal opens, but could the lack of data communication be the issue here?

export class TableRowExpandedComponent implements OnInit {

  @Input() postFromParent: Post

  constructor() {}

  ngOnInit() {}

}

I won’t delve into the entire modal HTML. Here’s what resides in the modal body:

 <p>{{postFromParent?.body}}</p>

Any assistance would be greatly appreciated.

PS, I am utilizing Angular CLI with Eclipse and have encountered some peculiar bugs (such as code not compiling unless I close and reopen the file), though it seems unrelated to this issue.

Answer №1

There are numerous methods to customize the behavior of this modal. One approach I prefer is to create a public open method in the modal component. This allows you to directly call it with specific data based on your desired conditions. Here's an example setup:

export class TableComponent {
  @ViewChild('modal') modal;

  selectRow(post) {
    this.modal.open(post);
  }

}

<app-table-row-expanded #modal> [postFromParent]="selected"</app-table-row-expanded>

The #modal serves as a reference to the component, which can be accessed using the @ViewChild decorator. Simply define your open method within the modal component like so:

export class TableRowExpandedComponent implements OnInit {

  public open(post) {
     // Implement logic here to display your content
  }
}

You can also access any @Inputs passed to the component in the usual manner.

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

Issue with Angular 11: A stream was anticipated but instead an improper object was provided. Acceptable options are Observable, Promise, Array, or Iterable

I'm well aware that there are numerous questions with similar titles and issues. I've dedicated the past day and a half to reading and experimenting with potential solutions, but unfortunately, none have worked for me. My situation varies slightl ...

Refreshing the browser does not load the Angular2 component and instead shows a 404 error

During my exploration of Angular 2, I developed a basic restaurant management application. Now, I am delving into more advanced techniques such as creating an app bundle, minification, and optimizing the application. The authentication component in my app ...

Is it necessary for me to be familiar with AngularJS in order to redesign an app for Angular 2+

I'm curious - when rewriting an application from AngularJS to Angular 2+, do you need to be familiar with both, or is knowing just Angular 2+ sufficient? ...

Comparing the Use of HttpHeaders Set versus Append in Angular

My caching interceptor is designed to check for the presence of an x-refresh header in incoming requests. If this header is found, it bypasses any cached request/response pairs associated with that specific endpoint and instead queries the server directly. ...

Angular 7 service utilizes HttpClient to retrieve stock data in the component's TypeScript file

Why am I getting an undefined result? I am using a contact API in my service to fetch data for the component HTML, but when I log the result, it is coming up as undefined. element: any ; constructor(private service: BlockService) { } ngOnInit() ...

Using Typescript to mute audio elements within HTML documents

I have a scenario where I want to mute audio that automatically plays when the screen loads. In order to achieve this, I am attempting to add a button that can toggle the audio mute functionality using Typescript within an Angular4 application. The code sn ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...

The subscriber continues to run repeatedly, even after we have removed its subscription

The file brief-component.ts contains the following code where the drawer service is being called: this.assignDrawerService.showDrawer(parameter); In the file drawer-service.ts: private drawerSubject = new BehaviorSubject<boolean>(false); public ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

Resolve the error message "Class is not a constructor" which arises while utilizing namespaces in TypeScript with WebPack

Issue with TypeScript Namespaces in PIXI.js As I delve into the world of TypeScript and PIXI.js without any framework, I find myself facing a challenge. Previously, at work, we utilized namespaces with the module keyword for a cleaner structure. However, ...

How should one properly format an array of objects with elements that are different types of variations?

I am currently developing a versatile sorting module using TypeScript. This module will take in an array of data objects, along with a list of keys to sort by. Once the sorting process is complete, the array will be sorted based on the specified keys. To ...

When utilizing Ionic components in Angular, you may encounter the error message "element not recognized."

I have recently developed an app using Ionic and Angular, but I am encountering a persistent error. Whether I place the HTML code in the default Ionic generated "pages" folder or in a custom page, the error persists. Ionic version 5.4.16 Angular version 1 ...

Express and Angular 5 service worker facing compatibility issues

For the past couple of days, I've been struggling with my Angular5 service worker. However, after some investigation, I believe the issue lies in the way I am serving the application. If you're interested in the detailed journey leading up to thi ...

Activate the button when a checkbox within a looping structure is selected using Angular 5

As a relatively new Angular 5 user, I am working with a button that looks like this: <button *ngIf="type!='invoices' && this.action==='edit'" disabled (click)="genera(fields.termini)" class="ml-16 mat-raised-button mat-accen ...

Upon refreshing the page, Vuex encounters an issue where it is unable to read

My website has a Navbar component that utilizes values from the Vuex store. Prior to entering each route, I trigger a dispatch from Vuex as shown below: router.beforeEach((to, from, next) => { //... store.dispatch("updateUserData"); ...

I'm looking to transform this array into the format described below, and also include another nested subarray within it using TypeScript

[{ "header": "API", "value": "hello" }, { "header":"API", "value":"yellow" }, { "header":"Other", "value":"yallow"}, { "header":"other", "value":"othertt" } ] I have a list of objects with he ...

The Angular 2 http request seems to be failing to reach the web api's get method when using a string parameter overload

Issue at hand is that the initial Get method gets triggered by this particular HTTP request: http://localhost:56690/api/testelements/?name=aeg One would anticipate the second (string overload) method to be invoked due to the presence of a string parameter ...

Expanding the table to display additional rows using pagination in an Angular application

I have implemented a table in Angular that displays data fetched from an API. The requirement is to initially display only the first 5 rows and provide an option for users to view more rows (in groups of 5) with pagination support. Below is the code snipp ...

The Datatable is displaying the message "The table is currently empty" despite the fact that the rows have been loaded through Angular

My experience with displaying a data table in Angular was frustrating. Even though all the records were present in the table, it kept showing "no data available." Additionally, the search function refused to work as intended. Whenever I tried searching for ...

WebWorker tends to be loaded intermittently on android devices

We have integrated a web worker in our Ionic application to handle certain computations. Previously, this setup functioned properly without any issues. However, suddenly we are encountering some challenges. Despite making significant changes throughout th ...