0

I need alerts (error messages) from child components to appear only on parent component, but these child components might be the only/main component on another page and need to show error messages themselves.

I am new to Angular and I am having some troubles. I have looked it up but I couldn´t find a answer for my requirements.

Using Observable and Subject I have a service injected in the components to share the error messages and an component to show them. Like mentioned in this link: https://stackoverflow.com/a/47441188

If I add 'app-error-msg' to both, parent and child components, the messages will appear on both components. I could put it only in the parent component, but I still want the messages in the child/crud components in case I use them as the main component in another page.

I am using Angular 7.

List/Select Component

<app-error-msg></app-error-msg>
<div>
    <!-- List and select components -->
</div
<app-crud-1 *ngIf="crud-1"></app-crud-1>
<app-crud-2 *ngIf="crud-2"></app-crud-2>
<app-crud-3 *ngIf="crud-3"></app-crud-3>

Crud Component

<app-error-msg></app-error-msg>
<form>
    <!-- Form Components -->
</form>

So, I would like to have one error message service, and make the messages appear on the main component of the page. Considering a child component in one page could be a parent/main component in another page. How can achieve it? Keeping the error msg service or not... What's the best way to do it?

Thank you.

Ddasol
  • 35
  • 7

1 Answers1

1

there is differents ways to manage this problem , in general you can use the classic child/parent communication by emitting a event to the parent using @Output() err = new EventEmitter(). your parent component can react to this event by

<child (err)="errHandler($event)"></child>

you can also use a Service that interact between child/parent

what I'm seeing based on your code the problem is not who is dispatch the error message, the issue is how the message is displayed in your view,

I will suggest to change a bit the structure of your app:

  • create a component (MessageComponent) that is included in your base app that will listen and render the actual error message ,
  • create a MessageServise that contain a Subject that will receive any message,
  • In the MessageComponent subscribe to the Subject ,listen and render the message
  • From any other component use the MessageService to dispatch the messages to the "MessageComponent"
Ricardo
  • 2,427
  • 19
  • 35
  • 1
    Ricardo's answer is the right one... I have to say I was already using his suggestions of a MessageComponent/MessageService/Subject... My dumb mistake is that I had the message component in more than one place (). So from his answer I want to highlight that the problem was how the message was being displyed in my view and that I should include the MessageCompoment in the base app only... any other component will use only the MessageService, to register the messages. – Ddasol Jun 19 '19 at 13:31