简体   繁体   中英

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?

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>

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

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";
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM