Answer the question
In order to leave comments, you need to log in
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;
}
}
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();
}
}
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
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 questionAsk a Question
731 491 924 answers to any question