Guide on integrating snackbar into a function within Angular 7

I currently have a mat-table with 6 columns. The 5th column displays the status of the job, which can be Completed, Running, or Pending. I've added two buttons - Stop and Re-Run. When a user clicks on the Stop button, I want the job to stop executing and display a snackbar notification. Similarly, clicking on the Re-Run button should trigger a snackbar notification as well.

To see a sample, you can check out this StackBlitz link.

Here is the HTML code:

<div class="main-content">
<mat-toolbar>
    <mat-progress-bar
        mode="indeterminate"
        class="mat-progress-bar"
        color ="primary"
    >
    </mat-progress-bar>
    &nbsp;&nbsp;
    <button
    mat-icon-button
    (click)="stop_exec_job()"
    matTooltip="Stop Executing the Job"
>
    <i class="material-icons" style="color:red"> stop </i>
</button>

</mat-toolbar>

<div class="card">
    <div class="card-header">
        <h5 class="title">Job Execution Stats</h5>
    </div>

    <mat-table [dataSource]="jobExecutionStat">
        <!-- Id Column -->
        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
            <mat-cell *matCellDef="let element">{{ element.id }} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="exec_date">
            <mat-header-cell *matHeaderCellDef>
                Execution Date
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.exec_date }}
            </mat-cell>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="curr_time_period">
            <mat-header-cell *matHeaderCellDef>
                Current Time Period
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.curr_time_period }}
            </mat-cell>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="prev_time_period">
            <mat-header-cell *matHeaderCellDef>
                Previous Time Period
            </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.prev_time_period }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="status">
            <mat-header-cell *matHeaderCellDef> Status </mat-header-cell>
            <mat-cell *matCellDef="let element"
                >{{ element.status }}
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="actions">
            <mat-header-cell *matHeaderCellDef> </mat-header-cell>
            <mat-cell *matCellDef="let element; let index = index">
                <button
                    mat-icon-button
                    (click)="stop_exec_job()"
                    matTooltip="Stop Executing the Job"
                >
                    <i class="material-icons" style="color:red"> stop </i>
                </button>
                <button
                    class="stop_btn"
                    mat-icon-button
                    color="#b71c1c"
                    (click)="re_run_job()"
                    matTooltip="Re-Run the Job"
                >
                    <i class="material-icons" style="color:green">
                        cached
                    </i>
                </button>
            </mat-cell>
        </ng-container>

        <mat-header-row
            *matHeaderRowDef="jobExecStatDisplayedColumns"
        ></mat-header-row>
        <mat-row *matRowDef="let row; columns: jobExecStatDisplayedColumns">
        </mat-row>
    </mat-table>
</div>

And here is the Typescript code:

import { Component, OnInit } from "@angular/core";
import { MatTableDataSource } from "@angular/material";
import { GlobalAppSateService } from '../../services/globalAppSate.service';
import { DataService } from '../../services/data.service';
import { SnakBarComponent } from '../custom-components/snak-bar/snak- 
bar.component';
@Component({
selector: "app-job-execution-screen",
templateUrl: "./job-execution-screen.component.html",
styleUrls: ["./job-execution-screen.component.scss"]
})
export class JobExecutionScreenComponent implements OnInit {
stop_btn: boolean = true;
re_run_btn: boolean = true;


jobExecStatDisplayedColumns = [
    "id",
    "exec_date",
    "prev_time_period",
    "curr_time_period",
    "status",
    "actions"
];

jobExecutionStat = new MatTableDataSource<Element>(ELEMENT_DATA);
constructor(private dataService: DataService, public globalAppSateService: 
GlobalAppSateService, private snakbar: SnakBarComponent ) {

}
ngOnInit() {
    const project = JSON.parse(this.dataService.getObject("project"));
    if (project != null) {
        this.globalAppSateService.onMessage(project);
    }
}


stop_exec_job() {

}
re_run_job() {

}
}
const ELEMENT_DATA: Element[] = [
{
    id: 1,
    exec_date: "17-01-2016",
    prev_time_period: "2016-04,2016-05,2016-06",
    curr_time_period: "2016-08",
    status: "Completed"
},
{
    id: 2,
    exec_date: "17-01-2017",
    prev_time_period: "2017-04,2017-05,2017-06",
    curr_time_period: "2017-08",
    status: "Running"
},
{
    id: 3,
    exec_date: "27-07-2017",
    prev_time_period: "2017-45,2017-46,2017-47",
    curr_time_period: "2018-01,2018-02",
    status: "Pending"
},
{
    id: 4,
    exec_date: "17-10-2018",
    prev_time_period: "2017-30,2017-31,2017-32",
    curr_time_period: "2018-01,2018-02",
    status: "Completed"
},
{
    id: 5,
    exec_date: "21-01-2018",
    prev_time_period: "2016-01,2016-02,2016-03,2016-04",
    curr_time_period: "2016-52",
    status: "Pending"
},
{
    id: 6,
    exec_date: "17-01-2018",
    prev_time_period: "2017-31,2017-32,2017-33,2017-34",
    curr_time_period: "2017-52",
    status: "Running"
}
];
export interface Element {
id: number;
exec_date: string;
prev_time_period: string;
curr_time_period: string;
status: string;
}

If for any reason the icons for 'stop' in red color and 'cached' in green color do not display properly, please note that they are intended to represent the actions of stopping and re-running respectively.

Answer №1

Upon reviewing your code, I noticed that you have used the following:

if(this.jobStatus == 'Running') {
  this.alert('Job Execution Stopped','Sucess');
}

this.jobStatus is actually an array containing all statuses (as declared at the top of the class).

To get the desired outcome, you will need to make the following changes:

(click)="stop_exec_job(element)"

I have included element as a parameter in the function.

stop_exec_job(element) {
        if(element.status == 'Running') {
            this.alert('Job Execution Stopped','Sucess');
        }
    }

By adding element as a parameter, I am now accurately checking the status of the element.

Please apply the same adjustment to the re_run_job function as well.

Answer №2

To integrate the SnackBar feature into your project, you can refer to this helpful link.

import {Component, Inject} from '@angular/core';
import {MAT_SNACK_BAR_DATA} from '@angular/material';

@Component({
  selector: 'your-snack-bar',
  template: 'displaying {{ data }}',
})
export class MessageArchivedComponent {
  constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) { }
}

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

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

Having trouble transferring file using Vue.js and Axios

I am attempting to send a file to a Java backend using axios and vue.js. The backend is functioning properly as I can successfully reach it using the provided curl command. curl --location --request POST 'http://localhost:8081/steg/aaa' --form &a ...

Can the Disqus API be leveraged to retrieve comments from a particular website address?

It is my preference to accomplish this task solely with client-side JavaScript scripting, if feasible. ...

using props to implement mappings in React

After fetching groups from my API, I am able to successfully see them in the UI and props. However, I am facing an issue where the group names are not being displayed. This is how I have mapped it: <List> {this.props.groups && this.prop ...

transitioning from angular 5 to the latest version of angular 7

After successfully migrating my application from Angular 5 to Angular 7, I made the necessary changes by replacing EventSource with EventSourcePolyfill as recommended during the application runtime. However, I am now encountering a peculiar issue. The cons ...

Is there a way to submit an object to the server without using ajax during form submission?

I have a web application built on the ASP.NET MVC 5 framework. One of the pages in my application utilizes the amazing jQuery-QueryBuilder plugin, allowing users to create filters to refine the dataset results. When a user submits the form by clicking the ...

Configuring a Selenium Firefox profile

While performing our tests, we came across an issue with how FireFox handles events when the browser is not in focus. We discovered that this problem can be resolved by setting up a FireFox profile with the preference "focusmanager.testmode" set to true ( ...

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

What is the process for changing the value type of a function in an already existing record?

Trying to create a function that transforms the definitions of object functions into different, yet predictable, functions. For example: converter<{ foo: (n: number) => void, bar: (s: string) => void }>({ foo: fooFunction, bar: barFunc ...

Discovering the optimum route within a 2D array given specific limitations using Dynamic Programming

Hey, I have a query related to dynamic programming (dp) that goes like this: Input: A 2D array of numbers Output: The maximum sum of a path from (0,0) to (n-1,n-1) with the following conditions: You can only move down and right i.e. from (A[i-1][j]) t ...

AngularJS not responding to double quotes in encoded format

I'm utilizing ngInit to transfer variables from PHP to my Angular JS Controller. Sometimes, the passed string may include encoded '"' (Double quotes ") <div data-ng-controller="UserController" data-ng-init='init({"test":"&q ...

How to get the total number of rows/records in a JSON store using ExtJS?

My dilemma involves a JSON store that provides data in JSON format. I am currently attempting to determine the number of rows or records in the JSON string. However, when utilizing the store.getCount() function, it consistently returns 0. Strangely, the ...

Easily generate a component directory complete with all essential files in just a few simple clicks

In my work with React and the typical app structure, I utilize a directory called src/components to store all of my React components. I am looking for a way to streamline the process of creating new components. I would like to be able to generate a compon ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

Guide on transferring selected table row using checkbox in HTML and sending the information to views.py file in Django

Hi there, I'm new to Python-Django and in need of help. I want to be able to pass the selected table row from a template to views.py with checkboxes checked using the POST method. Additionally, I would like to be able to select multiple rows. After su ...

How do I prevent the React <div id="root"></div> from disrupting the layout of my design?

I am working on implementing a ReactJS template, but the footer keeps breaking and I need it to stay at the bottom. The main culprit is the <div id="root"></div>. Does anyone know how to fix this issue? https://i.sstatic.net/xNRKe.png import ...

Value is not defined when subscribing to subject in Event Bus Implementation

After creating an EventBusService and EventData, here is the implementation: export class EventData { public eventName: string; public event: any; constructor(eventName: string, event: any) { this.eventName = eventName; this.e ...

Is there a way to implement a one-second delay before displaying a drop-down hover menu?

I've been trying to use the setTimeout function, but so far I haven't been able to figure out the correct way to do it. Any ideas on what I might be missing? JSFIDDLE $('.drop-down').click(function() { $(this).hide(); }); $(&apo ...

The RazorPay callback encountered an Uncaught TypeError indicating that the function is not recognized

In my TypeScript class, I have a defined handler as follows: "handler": function (response) { this.sendUserStatus(); }, Unfortunately, when I attempt to call this.sendUserStatus();, I encounter the following error: Uncaught Typ ...