JEET ADHIKARI
JEET ADHIKARI

Reputation: 539

Access constant in child component from Parent component

I have two components, I want to print the text in child component from the parent on click.

Parent Component :

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

@Component({
selector: 'parent',
templateUrl: 'parent.html'
})
export class ParentComponent implements OnInit {
   @ViewChild(ChildComponent) child;

   constructor() {
   }

   ngOnInit() {
   }

   click(){
       console.log(this.child.text);
   }
}

Child Component:

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

@Component({
selector: 'child',
templateUrl: 'child.html'
})
export class ChildComponent implements OnInit {

   constructor() {
   }

   ngOnInit() {
       const text = 'TEXT HERE';
   }

   //Some code...
}

I am new to angular. Just want to know how to make it work, I want some constants to be in one point and shared by others. Not necessary the constants has to be in child component only. Just need a good suggestion on how to make it work with a good coding strategy

This is not working for me.

Thanks

Upvotes: 0

Views: 761

Answers (2)

JB Nizet
JB Nizet

Reputation: 692281

textis a local variable of the ngOnInit method. It only exists in that method, and disappears when this method exists. You need to make it an instance field of the ChildComponent class:

export class ChildComponent implements OnInit {
   text: string;

   ngOnInit() {
       this.text = 'TEXT HERE';
   }
}

Upvotes: 0

Khaled Ahmed
Khaled Ahmed

Reputation: 1134

my solution is creating a sharedService between these two component

/// SharedService


export class SharedService {
   sharedConst: string = 'blabla';
}


//// ParentComponent


@Component({
    ...,
    providers: [SharedService]
})

export class ParentComponent {
    constructor(private sharedService: SharedService){}
}

//// ChildComponent

@Component({
    ...,
    template: `{{sharedService.sharedConst}}`
})

export class ChildComponent {


   constructor(public sharedService: SharedService){}
}

Upvotes: 1

Related Questions