Personalized Notification in Angular 2 Using Typescript

Seeking guidance on creating a customized alert in Angular2, I am facing challenges. Here's the alert box I want to replicate: check this example

Being new to Angular2 concepts, I need assistance in integrating this code into my Angular2 application. My app has a table with a submit button, and I aim to trigger an alert upon submission.

Visual Representation:

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

The code from my table.component.ts file:

import {Component, NgModule } from "@angular/core";
import { BrowserModule } from '@angular/platform-browser';
import {Http} from "@angular/http";

@Component({
    selector: 'demo',
    templateUrl: './app/table/table.component.html'
})

export class TableComponent{

    public data;
    constructor(private http: Http) {
    }

    ngOnInit(): void {
        this.http.get("app/table/data.json")
            .subscribe((data) => {
                setTimeout(() => {
                    this.data = data.json();
                }, 1000);
            });
    }

    addRow() {
        this.data.push({
            status:''
        })
    }

    deleteRow(index) {
        this.data.splice(index,1);
    }

    public toInt(num: string) {
        return +num;
    }

    public sortByWordLength = (a: any) => {
        return a.city.length;
    }
}

Content of my table.module.ts file:

import { NgModule }      from '@angular/core';
import { CommonModule }      from '@angular/common';
import { FormsModule } from "@angular/forms";
import { DataTableModule } from "angular2-datatable";
import { HttpModule } from "@angular/http";

import { TableComponent }   from './table.component';
import { DataFilterPipe }   from './table-filter.pipe';

@NgModule({
    imports: [
        CommonModule,
        DataTableModule,
        FormsModule,
        HttpModule
    ],
    declarations: [TableComponent, DataFilterPipe],
    exports: [TableComponent]
})

export class TableModule { }

Configuration details from app.module.ts:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }   from './app.component';
import { TableModule }   from './table/table.module';

@NgModule({
    imports: [BrowserModule, TableModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})

export class AppModule { }

Struggling to implement the mentioned code into my existing setup, seeking any form of help or advice. Thank you in advance!

Answer №1

If you're searching for it, NG2-BOOTSTRAP might be just what you need.

Take a look at the demonstration here:

Answer №3

When it comes to creating the alert you desire, there are a couple of approaches you can take. One option is to follow recommendations from fellow users and utilize Bootstrap or Material to achieve the desired alert.

Another suggestion on stackoverflow proposes utilizing a service to trigger a modal.

  1. Develop a service that manages the visibility of your alert.

import { Injectable } from '@angular/core';

@Injectable()
export class AlertService {

  alert = { 
    isVisible : false,
    message : ''
  };

  constructor() { }

  show(message){
    console.log('is visible');
    this.alert.isVisible = true;
  }

  hide(){
    this.alert.isVisible = false;
  }

}

  1. Integrate the alert into your app's root for universal use throughout the application.

<!-- simulated html -->
<header class='header'>Hello World</header>
<main> lorem ipsum </main>
<footer>The bottom of the world</footer>

<!-- alert dialog -->
<app-alert *ngIf="alert.isVisible"></app-alert>

  1. Ensure that the AlertService is imported into the intended view for activation.

import { Component } from '@angular/core';
import { AlertService } from '../alert.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

    private alertDialog;

    constructor(
      private alertSvc:AlertService
    ){
      this.alertDialog = this.alertSvc.alert;
    }
}

  1. Lastly, ensure you import the module as well.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AlertService } from './alert.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [AlertService],
  bootstrap: [AppComponent]
})
export class AppModule { }

I have only imported the alert service within the module to allow different pages to work with one central variable, in this case, the AlertService's alert object.

If you wish to explore another method by injecting directly into the DOM, consider studying Valor's bootstrap library for insights on how they achieved this (though I'm uncertain if direct injection into the DOM occurs).

Hopefully, this guidance proves useful!

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

Combining component attributes with a mixin in Vue 2 using TypeScript

In my Vue + TypeScript project, we are utilizing Vue class components. Recently, I moved one of the component's methods to a separate mixin that relies on the component's properties. To address TypeScript errors regarding missing properties in th ...

What is the solution for adjusting the dynamic routing in React using React Router v5 to redirect from /pageName to /my/pageName?

I find myself in a bit of a dilemma. Currently, I am utilizing React Router v5 for my website. Previously, my page links were structured as /pageName. However, in light of some new features, I have modified the links to be /:userId/pageName where userId c ...

The ag-Grid cellDoubleClicked event seems to be triggered twice when the cell is double clicked quickly, but functions correctly when double clicking at a slower

Currently, I am facing an issue in my Angular 8 project while using Ag-grid. The problem arises when I try to handle the double click event in ag-grid. Whenever the cellDoubleClicked event is triggered, a method is called twice if I quickly double click on ...

React's setstate function failed to properly update the state for an object that contains array elements

As a newcomer to Reactjs, I recently created a test code for managing different types of popups using state. The array is used to store all the popups, which are then stored in the state object. Whenever a popup is displayed, it is added to the array with ...

Upgrade your buttons with dropdowns from Bootsrap to ng-bootstrap for a fresh new look

Hello, I am new to Angular and I need help creating code for the ng-bootstrap. I am familiar with bootstrap-4 but not so much with Angular. I have tried following the Ng-bootstrap drop-down example from their website but it is not working for me. Can som ...

What is the process for applying this specific style to a certain element?

Here is an example of an element in an Angular2 app: <div class="ticket-card" [ngStyle]="{'background': 'url(' + ticketPath + ')' , 'background-size': 'cover'}"> I would like to enhance the style b ...

Efficient Typescript ambient modules using shorthand notation

Exploring the code snippet from the official module guide, we see: import x, {y} from "hot-new-module"; x(y); This syntax raises a question: why is 'x' not within curly brackets? What does this coding structure signify? ...

Tips for properly typing action creators connected to properties in react-redux

Within our project, all action creators are structured in the following manner: export const actionCreatorFunctionName(arg1, arg2...) { return (dispatch: Dispatch, getStore: () => StoreState) => { // ... function logic ... dispat ...

Exploring Angular Ag-Grid: Enhancing Row Expansion with a Simple Click

How can I increase the height of a particular row in Angular Ag Grid when clicked? I've edited the code in Stackbiz. Click here to see the edited data This is an example running from ag grid Tutorial Grid Tutorial Example ...

Upgrading from Ionic 3 to Ionic 5 API: A Comprehensive Guide

Hey there, I'm currently working on transitioning my Ionic 3 project to Ionic 5. While I've got a good handle on the component migration process, I'm running into an issue with Http, which is no longer supported. In the past, I used to call ...

Module 'xlsx' cannot be located

I encountered this issue while building with Jenkins on the server, but it works fine on my local machine without any errors: 15:07:39 "", 15:07:39 "", 15:07:39 "ERROR in src/services/excel.service.ts:2:23 - error TS2307: Cannot find module 'xlsx&apos ...

What is the best way to clear the parent component's content from the child component in Angular?

Having an issue with Angular routes. The URLs are functioning properly, but when I navigate to the child component, specifically CreateEventComponent, the parent component's content from EventsComponent is also displayed. How can I make sure that th ...

Is it possible for Typescript interface A to extend B while lacking certain properties from B?

My confusion lies in understanding how TypeScript interfaces function effectively. Here's what I currently have: import type { Socket, Handshake } from 'socket.io'; import type { Session } from './session'; export interface Sessio ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

Preflight CORS error 403, yet my header is correctly set

Currently developing an Ionic app that communicates with an API on a web server for database operations. A similar project was completed in the past, and I copied the code from there, but it's not functioning as expected. Below are the headers config ...

Error caused by CORS Policy blocking XMLHttpRequest access (Python/Angular)

I've encountered a troubling issue with my Angular application, currently live on the web. Users are unable to log in due to this issue, and those who are already logged in are experiencing issues while using the website. The error message reads: Acc ...

In MUI React, the opacity of the placeholder is customizable and can be easily adjusted. This allows for the placeholder to be hidden

Currently, I am facing an issue with a filled variant TextField from Mui React. I have tried to modify it using theme components, but the placeholder text becomes hidden when the field is not focused. See here for Before Focus And here for On Focus I hav ...

How can one efficiently deactivate all fields in an Angular form for a short period?

There are two ways I know to achieve this (demonstration of both available here). Both methods can be used for template-driven and reactive forms as they rely on the FormGroup API. formGroup.enable() and formGroup.disable() <form ngForm> <inpu ...

Having trouble resolving the npm ERR with @angular-devkit/[email protected]? Found the solution to fixing it by checking out @angular/[email protected] instead

When I try to update the local Angular CLI version, I keep encountering an error with this command: npm uninstall --save-dev angular-cli. (following instructions from this source) npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ER ...

Type guard does not narrow down the union type

Explore the following code snippet: type UnionType = 'foo' | 'bar' | 'baz' const obj = { foo: 'huh', bar: 'hmm' } function func(input: UnionType) { if(input in obj) { input } } In ...