How to dynamically load a component in Angular 7 with the click of a button

I am looking to implement a feature where clicking on a row in my table will load a specific component. In order to test this functionality, I have created a simple alert that pops up when a row is clicked displaying the message THIS ROW HAS CLICKED. This confirms that row clicking is functioning correctly.

However, my ultimate goal is to display the details of the clicked row by opening a separate component. You can view an example of what I'm aiming for in the mockup image below:

https://i.sstatic.net/E67hG.png

The table implementation shown below is used within the finished component:

finishing.component.ts

import { Component, OnInit } from '@angular/core';
import { Finished } from './finished.model';
import { FinishedService } from './finished.service';

@Component({
selector: 'ngx-finished',
styles: [],
template: `
    <ng2-smart-table
    [settings]="settings"
    (userRowSelect)="onCustomAction($event)"
    [source]="list"
    ></ng2-smart-table>
`
})
export class FinishedComponent implements OnInit {
    list: Finished[] = [];
    constructor(private service: FinishedService) {}

    ngOnInit() {
        this.service.getPatients().subscribe(actionArray => {
        let patients_data = actionArray.payload.get('data');
        if (patients_data) {
            this.list = patients_data;
        }
        });
    }

    settings = {
        add: {
            addButtonContent: '<i class="nb-plus"></i>',
            createButtonContent: '<i class="nb-checkmark"></i>',
            cancelButtonContent: '<i class="nb-close"></i>',
            confirmCreate: true
        },
        edit: {
            editButtonContent: '<i class="nb-edit"></i>',
            saveButtonContent: '<i class="nb-checkmark"></i>',
            cancelButtonContent: '<i class="nb-close"></i>',
            confirmSave: true
        },
        delete: {
            deleteButtonContent: '<i class="nb-trash"></i>',
            confirmDelete: true
        },
        view: {
            viewButtonContent: ''
        },

        columns: {
            nic: {
                title: 'NIC'
            },
            name: {
                title: 'Name'
            },
            address: {
                title: 'Address'
            },
            email: {
                title: 'Email'
            },
            haircolor: {
                title: 'Hair Color'
            }
        }
    };


    onCustomAction(event) {
        alert(`THIS ROW HAS CLICKED`);

    }
}

To achieve the desired functionality of loading the relevant component when a row is clicked, I need to make some modifications within the onCustomAction function:

onCustomAction(event) {
    I want to invoke the above mentioned component in here.
}

Answer №1

If you want to achieve this, you'll need to utilize routing. Follow these steps to implement it:

Start by setting up the routing in your application.

$ ng g module app-routing

Here is a sample routing setup with a default Home component and an Element component for the route /element

import { HomeComponent,ElementComponent} from './components';


const appRoutes: Routes = [ 
  { path: 'element', component: ElementComponent }, 
  { path: 'home',  component: HomeComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({ 
  imports: [ 
    RouterModule.forRoot( 
      appRoutes,
      { enableTracing: true } // <-- for debugging purposes 
    ) // other imports here 
  ], 
  ... 
}) 
export class AppModule { }

Next, update the app.module.ts file to include the reference to the routing

import { AppRoutingModule } from './app-routing/app-routing.module'; 

imports: [ BrowserModule, NgbModule, AppRoutingModule, ]

In the main component, make sure to add the routing component inside app.component.html

<router-outlet></router-outlet>

Finally, link the Angular component (e.g., HomeComponent.ts) to the routing

import { Component } from '@angular/core'; 
import { Router } from '@angular/router';

export class HomeComponent { 
  constructor( private router: Router ) {} 

  onCustomAction(event) { 
    this.router.navigate(['/element'])
      .then(success => console.log('navigation success?' , success))
      .catch(console.error); 
  } 
}

Answer №2

If you prefer displaying row details on the same page without utilizing routing, consider using angular material modal. Check out this link for more information:

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

The term 'Employee' is typically used as a classification, but in this context, it is being treated as a specific value

I am encountering an issue while trying to define a variable as type Employee. The error message 'Employee' only refers to a type but is being used as a value here. ts(2693) keeps appearing. Here is my show-api.ts code: import { Component, OnIni ...

The 'npm update' command seems to be failing when attempting to update dependencies within Angular2

I am looking to upgrade the outdated dependencies in my Angular 2 project. Upon running npm outdated, I identified several dependencies that need updating. However, when I attempt to update them using the npm update command, it does not seem to work as exp ...

Patience is key when waiting for one observable to respond before triggering another in Angular's async environment

What is my goal? I have several components with similar checks and data manipulation tasks. I am looking to centralize these tasks within an observable. To achieve this, I created an observable named "getData" in my service... The complexity lies in the f ...

From milliseconds to hours: a straightforward conversion

Given a start date, time and end date, time, I am trying to calculate the total travel duration. The output is in milliseconds and needs to be converted into hours format. Despite attempting some solutions shared here, I haven't been successful. < ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": https://i.sstatic.net/TvfEr.png This is how my media.component.ts file is structured: impo ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase: function Decorator(SampleClass: Sample) { console.log('Inside the decorator function'); return function (args) { console.log('Inside the high order function of the decorator: ', args); let sample = ...

Tips on toggling the visibility of an element in Angular 4

This is my unique html element: <ng-container> <span *ngIf="row.messageText && row.messageText.length >= 30 && expanded">{{row.messageText.substr(0, 25)}} <span>more</span> </span> ...

Troubleshooting a pair of distinct software programs: Angular and a web API

I am currently working on two separate applications, one developed in Angular and the other in web API. There is a function in my Angular application that calls a method in .NET Core. I would like to know if it is possible to debug the Angular function and ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image? Take a look at this component: countries.astro --- import type { Props } from 'astro'; const { country, description } = Astro.props as Props; --- & ...

Learning to integrate Socket.io into your FeathersJS service

I've been working on integrating Socket.io into my Feathersjs/Angular application and have successfully set up communication between the front and back ends. While I understand that the configuration in app.js is responsible for establishing server c ...

The image map library functions seamlessly with React but encounters issues when integrated with Next.js

I have been working on a client project that requires the use of an image map. I searched for a suitable library, but struggled to find one that is easy to maintain. However, I came across this particular library that seemed promising. https://github.com/ ...

What is the proper way to structure a React component class without any props?

When working with Typescript in a React project, the top level component typically does not receive any props. What is the recommended approach for typing this scenario? I have been using the following coding structure as a template, but I am curious if t ...

Availability of variables and declaration of functions

I'm having trouble accessing a variable in my Angular project. I am new to this, so please bear with me. Here's an overview of my project: app.component.html: <div> <ul> <li *ngFor='let var1 of Fcomponent' >{{var1}} ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Combining Bootstrap admin template with SCSS styling in Angular 2

Currently seeking a complimentary bootstrap template featuring scss style to incorporate into my angular project. Is there anyone who can guide me on the correct procedure for this task? I stumbled upon a potential template on github but I am having diffic ...

Tips for effectively passing query string parameters in Angular

I am looking to make an HTTP request with parameters through a query For instance: URL: https://api/endpoint?d=1&value=2 ...