3

I have two components header & a. In header component there is a hidden element and I want to show it from component a, but I don't know how do I do this.

header.component.html

<p>
  header works!
</p>
<div #hidden_element style="display: none">
  <h1>Hidden Element in header</h1>
</div>

a.component.html

<div (click)="show()">Show</div>

a.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {

  constructor() { }
  show() {
    // code to display hidden element in header component
  }
  ngOnInit() {
  }

}

app.component.html

<app-header></app-header>
<app-a></app-a>

1 Answer 1

1

You can do it by sending events between directives via a custom service. A simple example would look something like this:

// my-service.component.ts
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/index";

@Injectable()
export default class MyService {

    private messageSource = new Subject<string>();

    listener = this.messageSource.asObservable();

    send(message: string): void {
        this.messageSource.next(message);
    }
}

Your 'a' component will look something like this:

// a.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {

  constructor(private myService: MyService) { }

  show() {
    // code to display hidden element in header component
    this.myService.send('some message');
  }
  ngOnInit() {
  }

}

and this is your header component:

// header.component.ts
@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: []
})
export class HeaderComponent implements OnDestroy {

    private serviceSubscription: Subscription;

    constructor(private myService: MyService) { 
        this.serviceSubscription = this.myService.listener.subscribe(message => {
            // TODO: Do whatever you want to do here to show the hidden element
        });
    }

    ngOnDestroy(): void {
        this.serviceSubscription.unsubscribe();
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.