Call function from one component to another component Angularjs 2 [duplicate] - javascript

This question already has answers here:
How to communicate between component in Angular?
(8 answers)
Closed 5 years ago.
I want to pass value from one component to another component.
i.e., I need to pass value from Dashboard Component to Header Component
Here is my Dashboard Component
import{Component}from '#angular/core';
import { Header } from '../../layout/header.component';
export class Dashboard{
showAlert(id : any)
{
setItem(id);
}
}
Here is my Header component
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'header',
templateUrl: './header.component.html',
})
export class Header{
public setItem(id : any)
{
console.log('Exported value'+id)
}
}
But it is always giving Cannot find setItem
What is the mistake i am doing and how can i fix this ?
Note : I am doing this in Angularjs 2

If the element raises events, you can listen to them with an event binding. Refer to the angular doc https://angular.io/guide/template-syntax#event-binding for in depth knowledge.
Dashboard Component
import{Component}from '#angular/core';
import { Header } from '../../layout/header.component';
#Component({
selector: 'dashboard',
templateUrl: './dashboard.component.html',
})
export class Dashboard{
#Output() setItemEvent = new EventEmitter();
showAlert(id : any)
{
this.setItemEvent.emit(id);
}
}
Header component
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'header',
template: '<dashboard (setItemEvent)="setItem(param)"></dashboard>',
})
export class Header{
public setItem(id : any)
{
console.log('Exported value'+id)
}
}

You can use:
localStorage.setItem('name', 'value');
where name is the variable name you will use to access the value. You can access the value using:
var x = localStorage.getItem('name');

You can use event-binding like this :
////First Component
#component({
selector:'componentA',
})
export class ComponentA{
yourMethod(yourPassedParameter:any){...}
}
////// Second Component
#component({
selector:'componentB',
template: `<button (click)="yourMethod(yourParameter)">click</button>`
)
export class ComponentB{
#Output() eventLis = new EventEmitter();
yourMethod(yourParameter:any){...
this.eventLis.emit(yourData);
}
}
////Your crosscomponent
#component({
selector:'crosscomponent',
template: `<componentA #componentA></componentA>
<componentB (eventLis)="componentA.yourMethod(yourParameter)"></componentB>`
)
export class crosscomponent{
}

Related

HTML button onclick performs action on other HTML page

It is a simple problem but I cannot get around it as I am new to angular and web development. Basically there are two components home and dashboard. The button in home.component.html changes the source of the image from bulbOn.png to bulbOff.png. I want that the same button should also change the source similarly also on dashboard.component.html. I think I need to use typescript for that but I dont know how. Basically how should onClick on one html performs actions on other html?
home.component.html
<mat-card >
<button onclick="document.getElementById('myImage').src='assets/BulbOn.svg'">Turn on the bulb.</button>
<img id="myImage" src="assets/BulbOn.svg" style="width:100px">
<button onclick="document.getElementById('myImage').src='assets/BulbOff.svg'">Turn off the bulb.</button>
</mat-card>
dashboard.component.html
<mat-card class="bulbCard">
<div class="bulbimg"> <img src="assets/BulbOn.svg"> </div>
</mat-card>
dashboard.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.less']
})
export class DashboardComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
home.component.ts
import { Component } from '#angular/core';
import { User } from '#app/_models';
import { AccountService } from '#app/_services';
#Component({ templateUrl: 'home.component.html',
styleUrls: ['./home.component.less'] })
export class HomeComponent {
user: User;
constructor(private accountService: AccountService) {
this.user = this.accountService.userValue;
}
}
You should avoid manipulating the DOM like this with Angular.
And instead of using onclick, you should use Angulars event bindings. https://angular.io/guide/event-binding
<mat-card>
<button (click)="changeBulbState(true)">
Turn on the bulb.
</button>
<img [src]="bulbState ? 'assets/BulbOn.svg' : 'assets/BulbOff.svg'" style="width:100px">
<button (click)="changeBulbState(false)">
Turn off the bulb.
</button>
</mat-card>
Within your component's typescript add a variable for bulbState. The value of which will be changed when you interact with the buttons in your card.
The src of the image will change depending on if the bulbState variable is true or false.
import { Component } from '#angular/core';
import { User } from '#app/_models';
import { AccountService } from '#app/_services';
#Component({ templateUrl: 'home.component.html',
styleUrls: ['./home.component.less'] })
export class HomeComponent {
user: User;
bulbState: boolean;
constructor(
private accountService: AccountService,
private bulbStatusService: BulbStatusService
) {
this.user = this.accountService.userValue,
this.bulbStatusService.bulbStatus.subscribe(data => this.bulbState = value)
}
changeBulbState(state: boolean) {
this.bulbStatusService.changeBulbState(state);
}
}
In order to share this across multiple components I would suggest using a service.
https://medium.com/front-end-weekly/sharing-data-between-angular-components-f76fa680bf76
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs';
#Injectable()
export class BulbStatusService {
private bulbState = new BehaviorSubject(false);
bulbStatus = this.bulbState.asObservable();
constructor() { }
changeBulbState(state: boolean) {
this.bulbState.next(state)
}
}
What you would like to is to have a bulb state somewhere. Usually in Angular it's either the parent component which passes the state down to it's children or you can have a service to get/set the state. RxJS comes bundled with Angular and has some great utilities (observables) for sharing the state.
e.g. app-state.service.ts
import { BehaviorSubject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class AppState {
public readonly lightBulb = new BehaviorSubject<'on' | 'off'>('on');
}
Now inject this to you home component:
import { Component } from '#angular/core';
import { User } from '#app/_models';
import { AccountService } from '#app/_services';
import { AppState } from 'app-state.service';
#Component({ templateUrl: 'home.component.html',
styleUrls: ['./home.component.less'] })
export class HomeComponent {
user: User;
constructor(
private accountService: AccountService,
public state: AppState
) {
this.user = this.accountService.userValue;
}
}
In HTML:
<mat-card>
<button (click)="state.lightBulb.next('on')">Turn on the bulb.</button>
<img id="myImage" [src]="(state.lightBulb | async) === 'on' ? 'assets/BulbOn.svg' : 'assets/BulbOff.svg'" style="width:100px">
<button (click)="state.lightBulb.next('off')">Turn off the bulb.</button>
</mat-card>
Then do the same thing for dashboard component:
import { Component } from '#angular/core';
import { AppState } from 'app-state.service';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.less']
})
export class DashboardComponent {
constructor(public state: AppState) { }
}
And in HTML:
<mat-card class="bulbCard">
<div class="bulbimg"><img [src]="(state.lightBulb | async) === 'on' ? 'assets/BulbOn.svg' : 'assets/BulbOff.svg'"></div>
</mat-card>
So in the nut shell, Subjects are things that holds some value and that value can be changed with Subject.next([value here]).
Subjects are Observables and Observables can be subscribed to to get those values over time. In Angular we have async pipe which does this subscription for you and disposes that as well after the component is destroyed.
There are few things you could do better with this "observable store pattern" but here it is at it's simplest form.
Few notes related to other things: use (click) instead onclick as () is the Angular's way to bind outputs. Don't directly manipulate (or at least avoid) anything in DOM e.g. ´document.getElementById('myImage').src='assets/BulbOn.svg'´ but rather bind a value for that attribute with [] e.g. [bulbSvgSource] where ´bulbSvgSource´ would be defined in the component class.

Angular 6 #Viewchild is not working with lazy loading

Here is my code that gives error cannot read property title undefined.
Parent Component
import { Child } from './child.component';
#Component({
selector: 'parent',
})
export class ParentComponet implements OnInit, AfterViewInit {
constructor(){}
#ViewChild(Child) child: Child;
ngAfterViewInit(){
console.log("check data", this.child.title)
}
}
And Child Component is.
#Component({
selector: 'child',
})
export class ChildComponet {
public title = "hi"
constructor(){}
}
routing.module.ts is like
{
path: "",
component: ParentComponent,
children: [
{
path: '/child',
component: ChildComponent
}
]
}
And Gives error is
ERROR TypeError: Cannot read property 'title' of undefined(…)
I think you are missing 'template' or 'templateUrl' in relevance to creating a Component
ParentComponent
import { ChildComponent } from './child.component'; // {ChildComponent} not {Child} as we are referencing it to the exported class of ChildComponent
#Component({
selector: 'parent',
template: `<child></child>`
})
export class ParentComponet implements OnInit, AfterViewInit {...}
ChildComponent
#Component({
selector: 'child',
template: `<h1>{{ title }}</h1>`
})
export class ChildComponent {...} // Be sure to spell it right as yours were ChildComponet - missing 'n'
UPDATE as per the user's clarification on this thread
Had added a Stackblitz Demo for your reference (Check the console)
If you want to access the ChildComponent that is rendered under the Parent Component's <router-outlet> you can do so by utilizing (activate) supported property of router-outlet:
A router outlet will emit an activate event any time a new component is being instantiated
Angular Docs
ParentComponent's Template
#Component({
selector: 'parent',
template: `<router-outlet (activate)="onActivate($event)"></router-outlet>`
})
export class ParentComponent {
onActivate(event): void {
console.log(event); // Sample Output when you visit ChildComponent url
// ChildComponent {title: "hi"}
console.log(event.title); // 'hi'
}
}
The result will differ based on the visited page under your parent's children
If you visit Child1Component you will get its instance Child1Component {title: "hi"}
If you visit Child2Component you will get its instance Child2Component {name: "Angular"}
These results will then be reflected on your ParentComponent's onActivate(event) console for you to access
That's not how it's supposed to work. You'll be only able to get the ChildComponent in your ParentComponent ONLY if you have the <app-child></app-child> tag in your ParentComponent Template.
Something like this:
...
<app-child></app-child>
...
But since you're using child routing, and the ChildComponent will load on the router-outlet of your ParentComponent you won't have access to that using ViewChild
PS: You'll only have access to it inside ngAfterViewInit as ViewChild can only be considered safe to have instantiated after the View has loaded:
import { Component, OnInit, ViewChild } from '#angular/core';
import { ChildComponent } from '../child/child.component';
...
#Component({...})
export class ParentComponent implements OnInit {
#ViewChild(ChildComponent) childComponent: ChildComponent;
...
ngAfterViewInit() {
console.log(this.childComponent);
}
}
Here's a Working Sample StackBlitz for your ref that illustrates your scenario in both the cases.
PS: To get the ChildComponent properties in your ParentComponent, with Routing, you'll have to either use a SharedService or you'll have to pass the ChildProperty in the route as a QueryParam and read it in your ParentComponent using the ActivatedRoute
UPDATE:
Sharing Data using Route Query Params:
Although this won't make much sense, but in your ChildComponent, you can have a Link that would route the user to the ChildComponent with the title property passed as a queryParam. Something like this:
<a
[routerLink]="['/child']"
[queryParams]="{title: title}">
Go To Child Route With Query Params
</a>
And in your ParentComponent have access to it using ActivatedRoute like this:
...
import { ActivatedRoute } from '#angular/router';
...
#Component({...})
export class ParentComponent implements OnInit {
...
constructor(
private route: ActivatedRoute,
...
) { }
ngOnInit() {
this.route.queryParams.subscribe(queryParams => {
console.log('queryParams[`title`]', queryParams['title']);
});
...
}
...
}
Using a SharedService
Just create a SharedService with a private BehaviorSubject that would be exposed as an Observable by calling the asObservable method on it. It's value can be set by exposing a method(setChildProperty) that will essentially call the next method with the updated childProperty value :
import { Injectable } from '#angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
#Injectable()
export class SharedService {
private childProperty: BehaviorSubject<string> = new BehaviorSubject<string>(null);
childProperty$: Observable<string> = this.childProperty.asObservable();
constructor() { }
setChildProperty(childProperty) {
this.childProperty.next(childProperty);
}
}
You can then inject it both in your ParentComponent and in your ChildComponent:
In ChildComponent set the value:
import { Component, OnInit } from '#angular/core';
import { SharedService } from '../shared.service';
#Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
public title = "hi"
constructor(private sharedService: SharedService) { }
ngOnInit() {
this.sharedService.setChildProperty(this.title);
}
}
And in your ParentComponent get the value:
...
import { SharedService } from '../shared.service';
#Component({...})
export class ParentComponent implements OnInit {
...
constructor(
...,
private sharedService: SharedService
) { }
ngOnInit() {
...
this.sharedService.childProperty$.subscribe(
childProperty => console.log('Got the Child Property from the Shared Service as: ', childProperty)
);
}
...
}
Make sure inside your parent.component.html template you've added the <child></child> tag.

How to use the input of one component in another - Angular4

I'm a new in Angular and I have a problem: I need to use one variable from ComponentA in ComponentB So this is my code below (I need to use "favoriteSeason" input result in component "Result"
Component A
import { Component } from '#angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn }
from '#angular/forms';
import {MatRadioModule} from '#angular/material/radio';
import { ResultComponent } from '../result/result.component';
import { HostBinding } from '#angular/core';
#Component({
selector: 'app-answer-three',
templateUrl: './answer-three.component.html',
styleUrls: ['./answer-three.component.css']
})
export class AnswerThreeComponent {
disableBtn: boolean;
favoriteSeason: string;
seasons: string[] = ['Cheesburger', 'Cheesecake', 'Fondue', 'Pizza'];
submit() {
this.disableBtn = !this.disableBtn;
const result = this.favoriteSeason;
console.log(result);
}
}
<div class="co">
<mat-radio-group class="example-radio-group" [(ngModel)]="favoriteSeason" (ngSubmit)="submit()">
<div class="form-check">
<h1>Choose a food:</h1>
</div>
<mat-radio-button class="example-radio-button" *ngFor="let season of seasons" [value]="season">
{{season}}
</mat-radio-button>
</mat-radio-group>
<div class="example-selected-value">Your favorite food is: {{favoriteSeason}}</div>
<nav>
<div class="column">
<button class="btn btn-primary" [disabled]="disableBtn" name="button" (click)="submit()">save
</button>
<button class="btn btn-primary" [disabled]="!disableBtn" name="button" (click)="submit()">
<a routerLink="/result">Next</a>
</button>
</div>
</nav>
</div>
And I need to use the result of "favoriteSeason" in component Result
Component B
import { NgModule, Output } from '#angular/core';
import { Component, OnInit, Input } from '#angular/core';
import {Subject} from 'rxjs';
import { Injectable } from '#angular/core';
import { AnswerThreeComponent } from '../answer-three/answer-three.component';
import { HostListener } from '#angular/core';
#Component({
selector: 'app-result',
templateUrl: './result.component.html',
styleUrls: ['./result.component.css'],
})
export class ResultComponent {
#Input () answer: AnswerThreeComponent;
#Input () res: AnswerThreeComponent['submit'];
#HostListener('click')
click() {
const result = this.answer.favoriteSeason;
console.log(this.answer.favoriteSeason);
}
}
But i received an error - "can't find favoriteSeason name". What I do wrong? Thank you for any help and sorry if I wrote this question wrong (it's my first time)
Sanchit Patiyal's answer is correct, but I would like to elaborate on that.
When you use the #Input() decorator on a component's field, that means that you now can set that variable in a parent component's template. Consider the following example:
Component A:
#Component({
selector: 'aComponent',
templateUrl: './a.component.html'
})
export class AComponent {
inputValue: string;
//doesn't matter what you do here
}
<input [(ngModel)]="inputValue">
<bComponent [inputValue]="inputValue">
</bComponent>
Component B:
#Component({
selector: 'bComponent',
templateUrl: './b.component.html'
})
export class BComponent {
#Input() inputValue: string;
//this variable will be set by the parent component
}
<h1>{{inputValue}}</h1>
This is an example of one-way data flow, meaning that the data only flows into the component B. Now if you need to get some data out of the component, you need to use #Output() decorator, which uses an EventEmitter to emit events out to the parent component when something happens. Let's introduce the third component, cComponent:
#Component({
selector: 'cComponent',
templateUrl: './c.component.html'
})
export class CComponent {
#Output() output: EventEmitter<string>;
private counter: number;
click() {
this.output.next(counter++);
}
}
<button (click)="click()">Click me!</button>
...and then edit our AComponent like this:
#Component({
selector: 'aComponent',
templateUrl: './a.component.html'
})
export class AComponent {
inputValue: string;
buttonClicked(event: string) {
this.inputValue = event;
}
}
<cComponent (output)="buttonClicked($event)"></cComponent>
<bComponent [inputValue]="inputValue"></bComponent>
So, to recap, the component's output works just like other events (say (click) or (focus)), and can be used to get the data out of the component. HOpe this helps ;)
Welcome, by the way!
You can use RxJS BehaviorSubject for this. In this case we create a private BehaviorSubject that will hold the current value of the message which can be set in one component and get in other one. Follow this link for the tutorial.
Sharing Data Between Angular Components

Send data to all subscribers elements with observable - angular2

I want to send data to my all elements called 'modal', but only one of them reciving message.
I have a service:
#Injectable()
export class ModalService {
private _isOpen = new Subject();
isOpen$ = this._isOpen.asObservable();
open(id: string) {
this._isOpen.next({isOpen: true, id: id});
}
close(id: string) {
this._isOpen.next({isOpen: false, id: id});
}
and component:
import {Component, Input} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {ModalService} from './modal.service';
#Component({
selector: 'modal',
template: `
<ng-content></ng-content>`,
styleUrls: ['app/workshop/modal.component.css'],
providers: [ModalService],
})
export class ModalComponent {
#Input() ID;
private show = false;
constructor(private _modal: ModalService) {
this._modal.isOpen$.subscribe(
(value) => {
console.log(value)
if(this.ID === value.id) {
this.show = value.isOpen;
}
}
);
}
open() {
this._modal.open(this.ID);
}
close() {
this._modal.close(this.ID);
}
}
All works fine but the problem appear when i want inject service in any else Component and send message to rest of subscribers. I don't know how i can share message for all elements type of 'modal'. I can hook DOM element but i have problem with Component. How i can hook a all 'modal' elements to observable?
Thanks for help
In fact, you need to share the same instance to all these components. To do that, set the service in the providers attribute of the main component:
#Component({
(...)
providers: [ ModalService ]
})
export class AppComponent {
(...)
}

Using input/output events to trigger methods in a parent component in Angular 2

How can a child service notify a parent component of a change? I used to do this in angular 1 by $watching a variable in the child service. Unfortunately, this is no longer possible.
I tried injecting the service back into the component, but this fails, probably due to circular dependencies. Based on what I could find in current documentation, I came up with the code below:
AppComponent
|
SomeComponent
|
SomeService
AppComponent
#Component({
selector: '[app-component]',
templateUrl: 'partials/app.html',
directives: [
SomeComponent
],
providers: [
SomeService
]
})
export class AppComponent {
constructor() { }
}
bootstrap(AppComponent);
SomeComponent
import {Component, Input} from 'angular2/core'
import {SomeService} from '../services/some.service'
#Component({
selector: 'foo',
templateUrl: 'partials/foo.html'
})
export class SomeComponent {
constructor() {}
#Input set someEvent(value) {
console.log(value);
}
}
SomeService
import {EventEmitter, Output} from 'angular2/core'
export class CoreService {
constructor() {
this.someEvent = new EventEmitter();
}
#Output() someEvent: EventEmitter<any>;
public foo() {
this.someEvent.emit(true); // Or next(true)?
}
}
#Output must be used for components only not in services. At this level you can register on this event using the (...) syntax.
From the angular.io documentation (https://angular.io/docs/ts/latest/api/core/Output-var.html):
Declares an event-bound output property.
When an output property emits an event, an event handler attached to that event the template is invoked.
For a service you need to explicitly subscribe on this event, as described below:
import {Component, Input} from 'angular2/core'
import {SomeService} from '../services/some.service'
#Component({
selector: 'foo',
templateUrl: 'partials/foo.html'
})
export class SomeComponent {
constructor(service:CoreService) {
service.someEvent.subscribe((val) => {
console.log(value);
});
}
}

Categories