A
A
Alexander Sharomet2017-07-14 10:02:01
JavaScript
Alexander Sharomet, 2017-07-14 10:02:01

How to correctly pass a string from one component to another in Angular 4?

Hello. How to correctly pass a string from one component to another using a service.
Title Service

import { Injectable } from '@angular/core';
@Injectable()
export class TitleService {

  public title: String;

  constructor() {}

  setTitle(title: String){
    this.title = title;
  }
  getTitle(){
    return this.title;
  }
}

WrapperComponent
import { Component, OnInit } from '@angular/core';
import { TitleService } from '../../services/title.service';
@Component({
  selector: 'app-wrapper',
  templateUrl: './wrapper.component.html',
  styleUrls: ['./wrapper.component.css'],
})
export class WrapperComponent implements OnInit {

  title: String;
  constructor(private titleService: TitleService) { }

  ngOnInit() {
    this.title = this.titleService.getTitle();
  }
}

DashboarComponent
import { Component, OnInit } from '@angular/core';
import { TitleService } from '../../services/title.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  title = 'Dashboard';

  constructor(private titleService: TitleService) { }
  ngOnInit() {
this.titleService.setTitle(this.title);
}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
necotumusimnapsat, 2017-07-14
@sharomet

I recently just started with Angular myself, like, if the example above does not work, then you can try
Subject + Subscribe. From RxJs.
pseudo :
states.ts ->
(injectiable)
public title= new Subject();
Dashboard.ts ->
this.states.title.next('blabla');
Wrapper.ts ->
this.states.title.subscribe((value:string) => {
....
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question