selecting elements within an Angular 4 component using selectors

I've been working on developing a new message system that utilizes toaster notifications:

My main query revolves around expanding the capabilities to enable multiple alert components that can be specifically targeted within various templates.

For instance, in the root app.component.html template, it would include:

<alert root></alert>

While a sub component would contain:

<alert subcomponent></alert>

The current setup of the toaster tutorial (component) will target any instance of the alert component in a template.

If there were two instances, they both receive the same message when the service is activated.

My goal is to introduce an additional parameter in the service call:

this.alertService.success(message,target);

Answer №1

An attribute called target can be used in the alert directive component to specify a string input.

The alert component will only display when triggered by the alert service if the target matches:

alert.component.ts

// Include this input
@Input() target: string;

ngOnInit() {
    this.alertService.getAlert().subscribe((alert: Alert) => {
        // Check if the alert's target matches the component's target
        if (alert.target === this.target) {
            this.alerts.push(alert); 
        }
    });
}

alert.service.ts

// Each alert function accepts an additional target parameter, which can have a default value such as "root"

root.component.html

<alert target='root'></alert>

other.component.ts

// Triggering an alert
this.alertService.success(
    message='operation success', 
    target='root'
)

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

Using Angular2 to bind one-way data to a JSON attribute

Utilizing Angular2's one-way data binding, I am attempting to bind an input field value to a specific JSON property within the following object: [ { "name": "my name", "list": [ { "date": "0101970", "list": [ ...

Error when navigating to a dynamic parameter path using Angular Router

I'm trying to redirect a user to a path with a unique UUID when they go to the root URL (localhost:4200). However, I encountered the following error: ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'document/4fdb ...

Leveraging TypeScript's declaration file

Greetings! I am currently facing an issue while utilizing a declaration file in my TypeScript project. Here is the declaration file that I am working with: // Type definitions for Dropzone 4.3.0 // Project: http://www.dropzonejs.com/ // Definitions ...

What is the reason for certain packages not being placed in the vendor folder during an Angular 2 installation?

I recently created a basic project in angular 2 using their cli. I noticed that when I use 'node install --save' for a material design project, the files are stored in both node_modules and dist/vendor directories. However, when I installed angul ...

Sharing variables between components within the same file in Angular 6

I have an Angular 6 application that relies on APIs to function. Within my app, I need to display certain data from the APIs in an Angular Material Dialog. The dialog Component is located alongside the main component used to showcase the API data. However ...

Angular 4 incorporating a customized Bootstrap 4 accordion menu for seamless navigation

I am trying to implement a nested menu using a JSON object in Angular 4. Below is the code I have written. <div id="panel-group"> <div class="panel panel-default" *ngFor="let mainItem of objectKeys(my_menu); let i = index"> <div class ...

Modify the value of the <select> tag based on whether it is required or not

When utilizing a my-select.component within a form component, the following code snippet is used: <div *ngIf="items?.length"> <select [ngModel]="selectedItem" (ngModelChange)="valueChanged($event)"> <optio ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...

Angular 4 - Issue with Top Navigation Bar not remaining fixed at the top of the page

I'm having trouble finding a solution to keep the top navigation bar fixed at the top of the screen without allowing it to scroll when the page becomes too long. I want to prevent the top nav bar from scrolling and maintain its position at the top of ...

Calculating the annual total in angular 4 - a step-by-step guide

I have successfully calculated the sum of costs between each other, but now I am facing a challenge in summing up the total budget for the entire year. I have attempted to achieve this, but unfortunately, I am encountering an issue as it is showing me &apo ...

Deleting a NativeScript ImageAsset that was generated using the nativescript-camera module - Easy Steps!

import { takePicture, CameraOptions } from "nativescript-camera"; By setting saveToGallery to false in the CameraOptions, the image captured using takePicture is saved on my Android device in Internal Storage > Android > data > org.nativescript.a ...

Angular's HttpClient.get method seems to have trouble retrieving real-time data from a Firebase database

I have been debugging and I suspect that the error lies in this part of the code. The DataService class's cargarPersonas function returns an Observable object, but I am struggling to understand how to properly retrieve the database data and display it ...

What is the proper method for integrating a loader into an observable HTTP request?

I need to implement a "loading" variable for my login method: Here is the current login method: public login(authDetails:any):any{ return this.http.post<any>('https://myapi.com/session', authDetails).pipe( map(response => { ...

What is the best way to include generic HTML content in an Angular 2 component?

I am looking to design a versatile modal component that can accommodate various elements, ranging from text to images and buttons. If I were to implement something like the following: <div class="Modal"> <div class="header"></div> ...

Specifications for TypeScript Columns

Is there a way to create a comprehensive column definition map for various model types with proper typings in JavaScript? Let's explore how to achieve this: export type User = { id: number; admin: boolean; email: string; }; export type Book = { ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Angular button disable feature malfunctioning

In my current setup, I have included a date picker along with a save button. One issue I am facing is that the save button gets disabled when the date is not available. Despite the code working fine in most scenarios, there seems to be an issue with the di ...

Tips on using services for storing and fetching list data in Angular

I currently have two components, the "add-expense" component and the "view-list" component. The "add-expense" component collects expense details from a form and stores them as an object. My goal is to add this object to an empty list within the "expense-li ...

Guide to setting up identically named properties in Child container components

As I am still fairly new to React and its concepts, I may not be executing this correctly. Although the question might seem lengthy, I'll try my best to keep it simple. I have created a component for TableHead that extends some material-ui components ...

Encountering issues with utilizing global variables in Ionic 3

Using Ionic 3, I created a class for global variables but encountered an error Uncaught (in promise): Error: No provider for Globals! Error: No provider for Globals! at injectionError (http://localhost:8100/build/vendor.js:1590:86) at noProviderError Th ...