Roman Melnyk
Roman Melnyk

Reputation: 190

Access to the parent value from child component [Angular]

AppComponent (parent) has main page (layout) and counter of pages:

export class AppComponent {
  counter = '1/3';
}

<div class="counter">
  {{counter}}
</div>

There are also two components (children) that are responsible for the content of pages. From child components, need to have access to the parent value (counter).

One of them:

import {AppComponent} from '../app.component';

export class Page1Component {
  app: AppComponent;
}
SomeEvent($event) {
  this.app.counter='2/3';
}

<div class="content">
 ...
</div>

After the event I get an error: "TypeError: Cannot read property 'counter' of undefined"

Question: How to manipulate a parent variable correctly?

Upvotes: 0

Views: 5190

Answers (3)

JayDeeEss
JayDeeEss

Reputation: 1083

you can pass the parent variable to the child component through input property.

    import {Input} from '@angular/core';

    export class Page1Component {
      @Input() counter;

    SomeEvent($event) {
      this.counter='2/3';
    }
    }

and in your app you can pass the counter

app.component.html

<page1 [counter]="counter"><page1>

and if you want to change the counter of parent as well you can define an output event emitter and call the method in parent when some event occurs

Update if you want to change the couter of parent, you can try this:

import {Output} from '@angular/core';

export class Page1Component {
  @Output() change: EventEmitter<any> = new EventEmitter();

SomeEvent($event) {
  this.change.emit();
}
}

app.component.html

<page1 [change]="counterChanged()"><page1>

app.component.ts

export class AppComponent{
counterChanged() {
this.counter = "whatever value";
}

}

Upvotes: 1

Debabrata
Debabrata

Reputation: 498

you are doing this the wrong way you can't do this like that.. You have to do this in the following way by @Input tag

for example:

 export class AppComponent {
   counter = '1/3';
}

in the html of app component
<ChildComponent [counter]="counter"></ChildComponent>

in your child component

import { Component, Input } from '@angular/core';
export class ChildComponent{
        @Input() counter:any;

         //after this you can use counter
   }

more on this is here

Upvotes: 0

porgo
porgo

Reputation: 1737

Add input field in your child component:

@Input() counter: any;

And then you can bind to this porperty in parent html:

<child-component-selector [counter]="counter"></child-component-selector>

Upvotes: 1

Related Questions