Use variable of one component in another component in the same file

4.9k Views Asked by At

I have two components defined in the same file, and am trying to access one variable of a component into another, and got this answer, but the get SomeValue() function is not showing up in the other class when I try to refer to it.

Given answer on provided link:

export class Demo {
const sum = 10;

get SumValue() {
    return this.sum;
}
}

import-->Demo

export class Demo2 {
   private sum: number;
   this.sum = Demo.SumValue();
}

I can use a shared service, but don't want to use it just for one variable.

Is there something I'm missing from that answer?

1

There are 1 best solutions below

0
On

This is called Component Interaction

you need to use @Input for this.

If the property you want to send child is changing asyncronously, then you need to use EventEmitter

check this link for reference

here is simple example:

Child Component

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

@Component({
    selector: 'child-component',
    template: `<h2>Child Component</h2>
               current count is {{ count }}
    `
})
export class ChildComponent {
    @Input() count: number;
}

Parent Component:

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

@Component({
  selector: 'app-root',
  template: `
        <h1>Welcome to {{title}}!</h1>
        <button (click)="increment()">Increment</button>
        <button (click)="decrement()">decrement</button>
        <child-component [count]=Counter></child-component>` ,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Component Interaction';
  Counter = 5;

  increment() {
    this.Counter++;
  }
  decrement() {
    this.Counter--;
  }
}

Reference