0

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?

3
  • What is relation between those 2 component, for example its siblings or parent-child? Commented Dec 12, 2018 at 7:20
  • @R.Viral siblings Commented Dec 12, 2018 at 7:23
  • Might be you are missing @Input() in template Commented Dec 12, 2018 at 7:23

1 Answer 1

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.