How can a component be concealed in Angular while still permitting the passage of a function from the parent component?

Looking for a solution here:

<app-csv-confirm-dialog *ngIf="false" (confirmUpload)="addDataFromCSV()"></app-csv-confirm-dialog>

addDataFromCSV() {
  console.log('hi');
}

In the TypeScript file for csv-confirm-dialog, I have this code:

confirm(): void {
  this.confirmUpload.emit();
}

Unfortunately, it seems like the function is not being passed correctly as I'm not seeing 'hi' in the console. Is there a way to still pass the function from the parent to the csv-confirm-dialog even though it needs to be hidden since it's a popup dialog?

Answer №1

To handle the event emitter, the component must exist in the DOM. Otherwise, consider eliminating the event emitter and utilizing a singleton service. Here's an example:

shared.service.ts

@Injectable({providedIn: 'root'})
export class SharedService {
  private _confirmUploadSource = new BehaviorSubject<any>(null);
  public confirmUpload$ = this._confirmUploadSource.asObservable();

  public setUploadStatus(value: any) {
    this._confirmUploadSource.next(value);
  }
}

CsvConfirmDialog component

export class CsvConfirmDialogComponent implements OnInit {
  constructor(private sharedService: SharedService) { }

  confirm(value: any): void {
    this.sharedService.setUploadStatus(value);
  }
}

Parent component

export class AppComponent implements OnInit, OnDestroy {
  completed$ = new Subject<any>();

  constructor(private sharedService: SharedService) { }

  ngOnInit() {
    this.sharedService.confirmUpload$.pipe(
      takeUntil(this.completed$)
    ).subscribe(
      value => {
        console.log('hi');
        // perform actions from `addDataFromCSV()` function here
      }
    );
  }

  ngOnDestroy() {
    this.completed$.next();
    this.completed$.complete();
  }
}

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 narrowing TypeScript arrays often encountered

When working with arrays of strings in my TypeScript code, I restrict the contents to certain letters by using a defined type like ("A" | "B")[] for letters such as A and B. However, when I have a function that takes an arbitrary array ...

Setting the ariaLabel value in TypeScript is a straightforward process that involves defining the

In my TypeScript React application, I am attempting to dynamically set the ariaLabel value. However, ESLint is flagging an error: Property 'ariaLabel' does not exist on type 'HTMLButtonElement'. I have tried various types but none of t ...

Using Typescript to define the type for React's useState() setter function whenever

I'm working on setting up a React Context to handle parameters mode and setMode, which act as getter and setter for a React state. This is necessary in order to update the CSS mode (light / dark) from child components. I'm encountering a Typescr ...

Angular, manipulating components through class references instead of creating or destroying them

I am exploring ways to move an angular component, and I understand that it can be achieved through construction and destruction. For example, you can refer to this link: https://stackblitz.com/edit/angular-t3rxb3?file=src%2Fapp%2Fapp.component.html Howeve ...

"Launching" conduit for Observable

Is there a way to attach two pipes to an HttpClient request in order to execute functions at the beginning and end of the request? I have discovered the "finalize" operator for executing a function when the request is finished, but I am looking for an equi ...

Using TypeScript to specify precise types for ReactWrapper within the Enzyme library

During my testing process of custom components with jest and enzyme using typescript, I have been creating tests like this: const wrapper = mount(<MyCustomComponent/>); expect(wrapper).toMatchSnapshot(); As mount returns a type of ReactWrapper, I h ...

Angular Dynamic Alert Service

Is it possible to customize the text in an Angular Alert service dynamically? I'm looking to make certain words bold, add new lines, and center specific parts of the text. Specifically, I want the word "success" to be bold and centered, while the rest ...

Disable TS4023 error in TypeScript: Unable to name external module "xyz"

//custom-slice.js import { createCustomSlice } from '@my/data-toolkit'; /* ***********************For Managing all the divisions data****************************** */ export const divisionDataSlice = createCustomSlice({ name: 'divisionda ...

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Trouble with Vue3 Ref and Reactivity not displaying changes or updating

I'm seeking to grasp the concept of ref/reactivity in Vue3. Unfortunately, due to work constraints, we are unable to utilize any state management libraries. The objective is to manipulate the number of objects in an array and have the ability to edit ...

Error with the ng-select component in an Angular 8 project - Issue at Runtime involving the NgSelectComponent

I'm encountering issues with implementing ng-select in my Angular 8 application. The error I'm facing at runtime is: core.js:6249 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[NgSelectComponent -> NgSele ...

Can you provide some instances where Angular2 ag-grid pagination has been implemented?

Are there any examples of how to use ag-grid pagination with Angular2, particularly when it comes to virtual paging or infinite scrolling? I've been searching for a while but haven't found anything helpful. Any assistance would be greatly appreci ...

An error occurred in the ngrx store with Angular during production build: TypeError - Unable to access property 'release' of undefined

After deploying my application and running it, I encountered an issue that seems to be happening only during production build at runtime. At this point, I am uncertain whether this is a bug or if there is a mistake in my code. The error "TypeError: Cannot ...

Tips for activating automatic building of packages when utilizing pnpm install?

Our unique project is utilizing a combination of pnpm, workspace, and typescript in adherence to the monorepo standard. Upon cloning the repository, we execute a pnpm install command to download dependencies and establish links between local packages. De ...

Looking to update the state of a nested object with useReducer?

I am currently developing a Next.js application using Typescript and I need to make changes to a nested object state. Here is the structure of the state: const initialState ={ userInfo: string | null, isLoading: boolean, cursorState: boolean, compa ...

Nested interfaces can utilize sum types

An example showcasing the use of sum types: interface Cash { amount: number, type: 'cash' } interface Card { amount: number, type: 'card', cardNumber: string } type Payment = Cash | Card const displayPayment = (payment: Pay ...

Tips for transforming a Json array into an object in Angular 5

I am working with a Json array that looks like this: [{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}} ,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}} ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

Tips for setting up a hierarchical mat-table within a parent table that supports expandable rows using Angular Material

Here is the data that I am working with: [ { "_id": "c9d5ab1a", "subdomain": "wing", "domain": "aircraft", "part_id": "c9d5ab1a", "info.mimetype": "application/json", "info.dependent": "parent", ...

Tips on injecting configuration into forRoot

Is there a method to inject configuration object into AppModule's forRoot() function? How can I access the configService if there is no constructor within the module? config.yml: smtp: host: 'smtp.host.com' port: 10 secure: true aut ...