Nasco.Chachev
Nasco.Chachev

Reputation: 676

Angular 4 accessing other components data

I'm currently learning Angular 4 but I'm wondering if I can access one component's data from *.component.ts from another *.component.ts.. what do I mean? I have the following structure

app
  first-component
    first-component.html
    first-component.ts

  second-component
    second-component.html
    second-component.ts

  app(main)-component

So If I have for example the following array of strings in first-component :

 labels: any[] = ['Name' , 'Address' , 'Photo' , 'Date' , 'Session' , 'Description'];

Is there a way to access that array from my second-component.ts and to do something like this when labels array is declared in my first-component.ts?

second-component =>

  pushItemsToArray() {
    this.labels.push(item);
  } 

So If I have a form in my second-component and want to render the data in my first-component , how that happens? Thank you and sorry if the question is duplicate of another one, but I've been searching for a lot of time and couldn't find the things I was searching for..

Upvotes: 0

Views: 159

Answers (2)

rocktheartsm4l
rocktheartsm4l

Reputation: 2187

Sounds like the job for a service! For your example you could implement something like, label-service.ts. You can then inject LabelService into first component and second component.

To enable this you need to use the injectable decorator on the service class and add the LabelService class to your modules providers array.

In label service you will have an array of labels and some methods to help maintain them (add, remove, whatever you need).

@Injectable()
export class LabelService {
   labels: any[] = ['Name' , 'Address' , 'Photo' , 'Date' , 'Session' , 'Description'];

   addLabel(label): void {
      this.labels.push(label);
   }
}

This works if you are using the data in a template because then change detection will notice any changes. If you are going to do something more complex that you can't rely on change detection for you may end up needing to use Rxjs Subjects, angular 2 Input and Output decorators, or the ngOnChanges life cycle hook. (I can give more examples on a specific subject if you need, jsut ask)

Upvotes: 1

Tim Tharratt
Tim Tharratt

Reputation: 1310

The best way I've found it to use BehaviorSubjects, create a message service to facilitate this. This article explains this really well 4 methods to share data

I've posted sample code for such a service here

Upvotes: 1

Related Questions