unable to pass data between one component to another component in angular - javascript

I am trying to pass data from one component to another component I used the service file method.
I created two components one is login and the second is home. I have to pass data from login to home.
in the login component, I take user input, and the home component should print that.
I used this code below, but when I give input, it is not printing in output.
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class SharedService {
message : any;
constructor() { }
setMessage(data: any){
this.message=data;
}
getMessage(){
return this.message;
}
}
this is my home component code
import { Component, OnInit } from '#angular/core';
import { SharedService } from '../shared/shared.service'
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
message : string | undefined;
constructor(private shared:SharedService ) {}
ngOnInit() {
this.message =this.shared.getMessage()
}
}
<h1> {{ message }} </h1>
this is my login component code
import { Component, OnInit } from '#angular/core'
import { SharedService } from "../shared/shared.service"
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
message : any ;
constructor(
private shared: SharedService
) { }
ngOnInit(): void {
this.shared.setMessage(this.message)
}
}
<input required type="text" class="form-control" placeholder="Enter username" [(ngModel)]="message">

ofcourse it will not work this way .the reason it is not working . when you call SharedService in your constructor in box component it create an instance of your service with message : any . if you change it on one component it will not change on the other component .
what you can do is .
on your service . message = new Subject() ; setMessage(data: any){ this.message.next(data) ; }
you call set message on your login component . and on your home component you subscribe to the subject like this . this.sharedService.getMessage().subscribe( (result :any ) => {console.log(result )} .
sorry if this answer is messy , this is my first time using SOF .

Related

Angular app is compiling successfully but giving errors property does not exist in 'ng build --prod'

Angular app is compiling successfully but giving the following errors in 'ng build --prod'
ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent'.
src\app\dashboard\dashboard.component.html(3,72): : Property 'newsService' is private and only accessible within class 'DashboardComponent'.
src\app\dashboard\dashboard.component.html(3,72): : Property 'p' does not exist on type 'DashboardComponent'.
src\app\dashboard\dashboard.component.html(29,46): : Property 'p' does not exist on type 'DashboardComponent'.
I have used these properties in my html file as below:
header.component.htmlfile
<input type="text" class="form-control mr-2 align-self-center" required placeholder="Search" name="searchText" [ngModel]="searchText" value="">
dashboard.component.htmlfile
<pagination-controls class="text-center" (pageChange)="p = $event"></pagination-controls>
my header.component.html file
import { Component, OnInit, Output, EventEmitter, ViewEncapsulation } from '#angular/core';
import { NgForm } from '#angular/forms';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
filterText : string;
#Output() search = new EventEmitter();
#Output() filterButton = new EventEmitter();
constructor() { }
ngOnInit() {
}
onSubmit(form : NgForm)
{
console.log(form);
this.search.emit(form);
}
filterClicked($event)
{
this.filterText = $event.target.text;
this.filterButton.emit(this.filterText);
}
}
my dashboard.component.html file
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { NewsService } from '../shared/news.service';
import { NewsModel } from '../shared/news.model';
import { Form } from '#angular/forms';
import { Pipe, PipeTransform } from '#angular/core';
import { element } from 'protractor';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
articles : any;
temp : NewsModel = new NewsModel;
constructor(private newsService : NewsService) { }
ngOnInit() {
this.FetchHeadlines();
}
FetchHeadlines()
{
this.newsService.GetAllGaurdian()
.subscribe((result) =>
{
this.articles = result;
this.articles.response.results.forEach(element => {
this.newsService.newsArticles.push(this.newsService.CusotomMapper(element));
});
})
}
}
can't able to figure out where is the error exactly!
I think the error descriptions are as accurate as it can be. each of them tells you that something wrong with your component, lets examine each of them
ERROR:
ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent'.
you have searchText in HeaderComponent HTML, but not in the Component itself
SOLUTION: add searchText variable to the Component
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
searchText:string
...
}
ERROR :
src\app\dashboard\dashboard.component.html(3,72): : Property 'newsService' is private and only accessible within class 'DashboardComponent'.
all the fields you are using inside the template, must be the public field inside component itself, otherwise it will not compile
SOLUTION: change private modifier to public at newService
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor(public newsService : NewsService) { }
...
}
ERRORS :
src\app\dashboard\dashboard.component.html(3,72): : Property 'p' does not exist on type 'DashboardComponent'.
src\app\dashboard\dashboard.component.html(29,46): : Property 'p' does not exist on type 'DashboardComponent'.
same as HeaderComponent. you are using p field but it's not defined in DashboardComponent
SOLUTION : add p field to the dashboard component
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
p:any
...
}
You are trying to access from the template, variables that aren't defined in the corresponding components.
In header.component.html you are setting [ngModel]="searchText" and variable searchText isn't defined on header.component.ts. Could it be filterText variable instead?
In dashboard.component.html you are setting p = $event and variable p isn't defined on dashboard.component.ts. You also have an error about newsService being private. If you are gonna use it in the template it must be declared public when you inyect it on the constructor. I hope this helps. If you need more help is better if you provide a Stackblitz with minimum code.

How do I pass data from one component to another (New Browser Tab) in angular?

I'm new to angular and I don't know how to pass data between two components using routers. This is my first component view,
when I press view report button I need to call another component with the first component data. This is my first component view report click button code.
<button type="button" (click)="onFuelViewReport()" class="btn btn-success ">
<b>view Report</b>
</button>
when clicking the button it calls onFuelViewReport() function in the first component and using this function it opens the second component view with a new browser window (tab). What I want is to pass data from the first component to the second component from here. Please help me to do this.
onFuelViewReport() {
this.router.navigate([]).then(result => {
window.open("/pages/view-report", "_blank");
});
}
If you want to share data from child component to parent component, you can use #Output event emitter or if your are trying to share data within unrelated components, you can use BehaviourSubject (This also works in case of parent to child component communication and vice versa).
Child to Parent: Sharing Data via Output() and EventEmitter
parent.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-parent',
template: `
Message: {{message}}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
child.component.ts
import { Component, Output, EventEmitter } from '#angular/core';
#Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hola Mundo!"
#Output() messageEvent = new EventEmitter<string>();
constructor() { }
sendMessage() {
this.messageEvent.emit(this.message)
}
}
Unrelated Components: Sharing Data with a Service
data.service.ts
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs';
#Injectable()
export class DataService {
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
}
parent.component.ts
import { Component, OnInit } from '#angular/core';
import { DataService } from "../data.service";
#Component({
selector: 'app-parent',
template: `
{{message}}
`,
styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
}
sibling.component.ts
import { Component, OnInit } from '#angular/core';
import { DataService } from "../data.service";
#Component({
selector: 'app-sibling',
template: `
{{message}}
<button (click)="newMessage()">New Message</button>
`,
styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
newMessage() {
this.data.changeMessage("Hello from Sibling")
}
}
The window.open looks absolutely awful. Use this.router.navigate(['/heroes']);.
So if I understand correctly you have a list of items and when you click on one of the items, the details page of that item should open?
Best practice is to allow the detail route to have a property to set. the Angular Routing & Navigation page is very complete. It shows that you should use :id - { path: 'hero/:id', component: HeroDetailComponent }. When you open the detail page, you get the id variable and then get the data for it.

wait till the request completes in angular

In my angular application, I have one parent component i.e. Dashboard Component having 2 Sub Components i.e. Analytics Component & Stats Component. My dashboard.component.html looks like this
<div class="row">
<div class="col-lg-6"><app-analytics></app-analytics></div>
<div class="col-lg-6"><app-stats></app-stats></div>
</div>
I am also using a Global Component which is available to all the components works like a global storage. Now in the dashboard.component.ts. I am making a HTTP call to the server, getting the data and saving it into the Global component.
dashboard.component.ts
import { Component, OnInit } from '#angular/core';
import { Global } from 'app/shared/global';
import { Http } from '#angular/http';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor(private http : Http){
};
ngOnInit(){
this.http.get('/api/getUserPreferences').subscribe(response=>{
var data = response.json();
Global.userPreferences = data.preferences;
})
}
User preferences I am using in the sub components i.e. Analytics Component and Stats Component.
analytics.component.ts
import { Component, OnInit } from '#angular/core';
import { Global } from 'app/shared/global';
import { Http } from '#angular/http';
#Component({
selector: 'app-analytics',
templateUrl: './analytics.component.html',
styleUrls: ['./analytics.component.css']
})
export class AnalyticsComponent implements OnInit {
public analyticsUserPreferences : any;
constructor(private http : Http){
};
ngOnInit(){
this.analyticsUserPreferences = Global.userPreferences.analytics;
// Printing just for the question purpose
console.log(this.analyticsUserPreferences);
}
}
stats.component.ts
import { Component, OnInit } from '#angular/core';
import { Global } from 'app/shared/global';
import { Http } from '#angular/http';
#Component({
selector: 'app-stats',
templateUrl: './stats.component.html',
styleUrls: ['./stats.component.css']
})
export class StatsComponent implements OnInit {
public statsUserPreferences : any;
constructor(private http : Http){
};
ngOnInit(){
this.statsUserPreferences = Global.userPreferences.stats;
// Printing just for the question purpose
console.log(this.statsUserPreferences);
}
}
Now, in these sub components. I am getting undefined every time in the console. Is there any way that it should wait till the Global.userPreferences doesn't contain the values. Or is there other way to do the same. I just want that it should wait till the http request is completed and print whenever the values are store inside the Global.userPreferences.
You can use the async pipe and an *ngIf to wait for the http request to be completed before rendering the child components. Then use binding to pass the data down to the child component and receive it with an #Input().
dashboard.component.ts
public userPreferences$: Observable<any>;
ngOnInit(){
this.userPreferences$ = this.http.get('/api/getUserPreferences').subscribe();
})
dashboard.html
<app-analytics *ngIf="userPreferences$ | async as userPreferences" [userPreferences]="userPreferences"></app-analytics>

updating variable in angular Service

I am new to angular and trying to update variable but I variable is not updating in view. I am accessing a variable "name" created in service and updating it but it isn't working. When I call clickme() the value of variable name doesn't update on the webpage and shows old value "no name". I want to change the variable name value to "rahul" and display it on the page.
my service:
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class FirstService {
name:string="no name"
setName() {
this.name="rahul"
}
}
code:
import { Component, OnInit } from '#angular/core';
import { FirstServiceService } from './first-service.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [FirstService]
})
export class AppComponent implements OnInit {
account:any
name:string
constructor(private userName:FirstService){ }
ngOnInit(): void {
this.name=this.userName.name
}
clickMe(e){
this.userName.setName()
}
}
You usually do with this way:
Service
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class FirstService {
private name:string="no name";
setName(_name: string): void {
this.name = _name;
}
getName(): string {
return this.name;
}
}
Component
import { Component, OnInit } from '#angular/core';
import { FirstService } from './first-service.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [FirstService]
})
export class AppComponent implements OnInit {
account:any
name:string
constructor(private firstService: FirstService){ }
ngOnInit(): void {
this.name=this.firstService.getName();
}
clickMe(e){
this.userName.setName("rahul");
this.name=this.firstService.getName();
}
}
Whereas I must admit that the value of name normally doesn't get set by the same method that afterwards consumes it from the service. At least not when these are the only 2 lines of code in the method, though. But I reckon you're still playing around a little with services and then it's okay.
There is no need to set the same variable name in service like component.You can use anything you want.
In App component
clickMe(e){
this.name=this.userName.setName();
}
In service
getName() {
return this.name;
}
I hope it will help
You only equals the variable "name" to this.userName.name in OnInit, this is the reason because you don't see any change -you're showing the variable "name", not the variable this.usuerName.Name.
Normally you can use some simple, it's a getter
You can write in component
export class AppComponent implements OnInit {
account:any
//NOT have a variable "name", just a getter
get name(){
return this.userName.name;
}
//even if you want you can write
set name(value)
{
this.userName.name=value;
}
constructor(private userName:FirstService){ }
ngOnInit(): void {
}
clickMe(e){
this.userName.setName()
//or this.name="George"; //if you include the function set name()
//or this.userName.name="George"
}
}

html wont render from inside angular 2 component

I'm using a service to dynamically change the content in my header depending on the page I'm on, however when I put HTML in my component it doesn't render in the browser (see example below)
home.component.ts
import { Component, OnInit } from '#angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(
private headerTitleService: HeaderTitleService
) { }
ngOnInit() {
this.headerTitleService.setTitle(`
We strive to create things
<br> that are engaging, progressive
<br> & above all
<span class="highlight">
<em>innovative.</em>
</span>
`);
}
}
header.component.ts
import { Component, OnInit } from '#angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
title: any;
constructor(
private headerTitleService: HeaderTitleService
) { }
ngOnInit() {
this.headerTitleService.title.subscribe(updatedTitle => {
this.title = updatedTitle;
});
}
}
header.component.html
<h1>{{title}}</h1>
so Im trying to set the title to be a string that has html tags in it that I want to be rendered but what happens is the whole thing comes out as a string instead of how it would look like it I had put it in my home.component.html.
Is there a way I can do this??
You can set the [innerHtml] property
<h1 [innerHtml]="title"></h1>
Example

Categories

Resources