How to change parent variable from children component?

Mdkusuma picture Mdkusuma · Jan 16, 2017 · Viewed 22.5k times · Source

This question is quite simple but I can't get rid of it.

I have a <header> in parent template and I need it disappear when displaying children template through routing module. What I expect is adding a class to the header tag so I can hide it via CSS. This is what I have:

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app',
  template: `
    <header [class.hidden]="hide">
      <h1>My App</h1>
      <ul>
            <li><a href="/home"></a></li>
            <li><a href="/showoff"></a></li>
      </ul>
    </header>
    <router-outlet></router-outlet>
  `
})

export class AppComponent {
  hide = false; // <-- This is what I need to change in child component
}

app-routing.module.ts

import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './welcome.component';
import { ShowOffComponent } from './show.off.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'showoff', component: ShowOffComponent },
];

export const AppRouting = RouterModule.forRoot(routes, {
  useHash: true
});

show.offf.component.ts

import { Component } from '@angular/core';
@Component({
   selector: 'app-showoff',
   template: `
       <h2>Show Off</h2>
       <div>Some contents...</div>
   `
})

export class ShowOffComponent {
   hide = true; // <-- Here is the problem.
                // I don't have any idea how to reach parent variables.
}

Answer

Suraj Rao picture Suraj Rao · Jan 16, 2017

You can use output emitter

In your child component,

import { Component } from '@angular/core';
@Component({
   selector: 'app-showoff',
   template: `
       <h2>Show Off</h2>
       <div>Some contents...</div>
   `
})

export class ShowOffComponent {
    @Output() onHide = new EventEmitter<boolean>();
    setHide(){
       this.onHide.emit(true);
    }
}

In the parent,

export class AppComponent {
  hide = false;

  changeHide(val: boolean) {
    this.hide = val;
  }
}

Add a child to the parent with that event emitter,

<app-showoff (onHide)="changeHide($event)"></app-showoff>