Angular 8: send event from one component to sibling component - javascript

I have a sidebar component and a page component.
The sidebar component has a #ViewChild which is an ngbAccordion from Angular Boostrap. I want to trigger its collapseAll method from the page component.
So the sidebar has
#ViewChild('webAccordion', { static: false })
webAccordion: NgbAccordion;
#ViewChild('pageAccordion', { static: false })
pageAccordion: NgbAccordion;
collapseAllAccordions() {
this.webAccordion.collapseAll();
this.pageAccordion.collapseAll();
}
When the "page" component loads, I want to emit an event to the "sidebar" component that triggers my collapseAllAccordions function.
I know how to do this with parent/child components, and most of the stuff I can find with Google and here on SO discusses parent/child situations. Except in my case they are sibling components. I'm not sure how to hand siblings.

You can use a service:
Inject a service into two sibling components.
Add an emitter or an Observable to the service.
Add a function in the service to change the value of the Observable / emit a new value if your using an emitter.
Use the function in your "page" component.
Subscribe to the emitter or the Observable in your "sidebar" component and trigger collapseAllAccordions.

You could use intermediate singleton service between these components and share the data/actions. For example,
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss']
})
export class SideBarComponent implements OnInit {
constructor(private service: AppService) { }
onClick() {
this.service.collapse();
}
ngOnInit(): void { }
}
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-page',
templateUrl: './page.component.html',
styleUrls: ['./page.component.scss']
})
export class PageComponent implements OnInit {
constructor(private service: AppService) {
// Create a observable object which listens to service and
// change the behaviour of current page component and vice versa
}
ngOnInit(): void { }
}
If you require further assistance please create stackblitz or codesandbox to replicate this issue.

Related

Angular - trying to use child component function in parent view but I'm gettting an error

When I use #ViewChild I get the error that the component is not defined.
When I use #ViewChildren I get the error that the function from that component is not a function.
I am new to using child components in Angular so I'm not sure why it's doing this when I do have the child component defined in the parent component and when it's clearly a function in the child component.
I don't want to have to define every function from the child in the parent or else what's even the point of using a separate component.
Child Component
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-mood',
templateUrl: './mood.component.html',
styleUrls: ['./mood.component.css']
})
export class MoodComponent implements OnInit {
moodColors = ['red', 'orange', 'grey', 'yellow', 'green'];
constructor() { }
ngOnInit(): void {
}
chooseMood() {
alert(this.moodColors);
}
}
Parent Component (Relavant Part of Version with "ERROR TypeError: ctx_r3.mood is undefined")
import { Component, OnInit, ViewChild, ViewChildren } from '#angular/core';
import { ViewEncapsulation } from '#angular/core';
import { MoodComponent } from '../mood/mood.component';
#Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CalendarComponent implements OnInit {
#ViewChild('mood') mood: MoodComponent = new MoodComponent;
Parent Component (Relavant Part of Version with "ERROR TypeError: ctx_r3.mood.chooseMood is not a function")
import { Component, OnInit, ViewChild, ViewChildren } from '#angular/core';
import { ViewEncapsulation } from '#angular/core';
import { MoodComponent } from '../mood/mood.component';
#Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CalendarComponent implements OnInit {
#ViewChildren('mood') mood: MoodComponent = new MoodComponent;
Parent View
<h2 (click)="mood.chooseMood()"></h2>
You don't explicitly initialize view children via new.
Just use:
#ViewChild('mood') mood : MoodComponent;
If that doesn't work post a Stackblitz example which I can edit to resolve the issue.
Also, using ViewChild is more of an exception in Angular, and your use of it points to a probable design issue. More likely you child component should emit via an Output to the parent.
Regarding outputs, you can do something like this - though it is hard to give a precise answer without deeper knowledge of what you are trying to achieve:
export class MoodComponent implements OnInit {
#Input() moodId: string;
#Output() chooseMood = new EventEmitter<string>();
moodClicked(){
this.chooseMood.emit(moodId);
}
}
export class CalendarComponent implements OnInit {
moodChosen(string: moodId){
console.log(moodId);
}
}
// Calendar template:
<app-mood
moodId="happy"
(chooseMood)="moodChosen($event)"
></app-mood>
1 - you have to use this code
#ViewChild('mood') mood : MoodComponent;
when you are using #ViewChildren it will return list of items with the 'mood' name then you have to use this code
mood.first.chooseMood() ;
its better use ViewChildren when there is ngIf in your element
2- no need new keyword for initialize mood variable
it would be fill after ngOnInit life cycle fires

Angular 4+ send service from child to parent via interface

I was searching for answer several hours..
Is possible in angular to send from child to parent service via interface?
parent component
child component (extends parent)
interface for service
service (e.g. locationService) (implementing iface above)
Child extends from Parent
constructor(public locationService: LocationService) {
super(locationService); //parent
}
And parent looks like:
constructor(generalService?: IService) {
this.myService = generalService;
}
and than I want to do something like: this.myService.doLogic();
I got runtime error: Error: Uncaught (in promise): Error: Can't resolve all parameters for ParentComponent: (?).
Thanks for any hint or help..
The best way to design component inheritance in Angular framework is passing Injector instance to base component and injecting dependencies in the base component.
Base component class implementation:
export class BaseComponent {
protected locationService: LocationService;
constructor(injector: Injector) {
this.locationService = this.injector.get(LocationService);
}
}
Child component:
import { Component, Inject, Injector } from "#angular/core"; // Import injector from #angular/core
#Component({
selector: "child-component",
templateUrl: "child-component-template.html",
styleUrls: [
"./child-component-styles.scss"
]
})
export class ChildComponent extends BaseComponent{
constructor(
#Inject(Injector) private injector: Injector
) {
// Pass injector instance to base class implementation
super(injector);
}
}
Now in the child component you can use LocationService by calling this.locationService.doSomethind();
You should not have to extend Component, By extending component it brings only class property. So change parent from Component to simple class.
interface IService {
doLogic();
}
#Injectable()
export class LocationService implements IService {
doLogic() {
console.log('service goes here...');
}
}
export class ParentComponent {
constructor(public locationService?: IService) {
}
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent extends ParentComponent {
constructor(locationService: LocationService) {
super(locationService);
this.locationService!.doLogic();
}
}

Angular2 view not updating after model is set from another component

I have a simple web app that has an app model and a couple of components. When I update an array that I have in my model the view where that model is being consumed does not update. When I console log the model array I can see the model being updated just not the view. Any help would be greatly appreciated. Below please have a look at what I currently have.
overview.component.ts
import { Component, OnInit } from '#angular/core';
import { AppModel } from '../models/app-model';
#Component({
selector: 'app-overview',
templateUrl: './overview.component.html',
providers: [AppModel]
})
export class OverviewComponent implements OnInit {
constructor(public AppModel:AppModel) { }
ngOnInit() {}
}
app-model.ts
export class AppModel {
myArray:Array<any> = [];
constructor(){}
}
overview.component.html (This is the view that is not being updated when the model gets updated)
<td *ngFor="let dataItem of AppModel.myArray">
<span{{ dataItem }}</span>
</td>
This is how I am updating the array in the app model from another component
import { Component, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
import { AppService } from '../services/app.service';
import { AppModel } from '../models/app-model';
#Component({
selector: 'other-component',
templateUrl: './other-component.component.html',
providers: [AppService, AppModel]
})
export class OtherComponent implements OnInit {
constructor(private http: Http, public AppService:AppService,public AppModel:AppModel) {}
private updateModel() :void {
this.AppModel.myArray = someArray;
}
ngOnInit() {}
}
For a service you get an instance per provider.
If you add a provider to a component, you get as many service instances as you have component instances. Only the component itself and it's children can inject a provider from a component.
You either need to provide the service on a common parent component or in #NgModule().
With providers only in #NgModule() you get a single instance for your whole application

Making a reusable angular2 component that can be used anywhere on the a site

Use Case: When making asynchronous calls, I want to show some sort of a processing screen so that end users knows something is happening rather than just staring at the screen. Since I have multiple places throughout the site where I want to use this, I figured making it a component at the "global" level is the best approach.
Problem: Being slightly new to angular2, I'm not getting if this is a problem of it being outside the directory in which the main component exists and the OverlayComponent being in another location or if I'm just all together doing it wrong. I can get the component to work fine but I need to be able to call functions to hide/destroy the component and also display the component. I have tried making it a service but that didn't get me any further so I'm back to square one. Essentially my question revolves around building a reusable component that has methods to hide/show itself when invoked from whatever component it's being called from.
Below is my current code:
Assume OverlayComponent.html is at /public/app/templates/mysite.overlay.component.html
Assume OverlayComponent.ts is at /public/app/ts/app.mysite.overlay.component
Assume mysite.tracker.component is at \public\app\ts\pages\Tracker\mysite.tracker.component.ts
OverlayComponent.html
<div class="overlay-component-container">
<div class="overlay-component" (overlay)="onShowOverlay($event)">
<div>{{processingMessage}}</div>
<div>
<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>
</div>
</div>
</div>
OverlayComponent.ts
import { Component } from '#angular/core';
#Component({
selector: 'overlay-component',
templateUrl: '/public/app/templates/mysite.overlay.component.html',
styleUrls: ['public/app/scss/overlay.css']
})
export class OverlayComponent {
onShowOverlay(e) {
$('.overlay-component').fadeIn(1000);
}
hideOverlay(e) {
$('.overlay-component').fadeOut(1000);
}
}
TrackerComponent.ts
import { Component, Output, OnInit, EventEmitter } from '#angular/core';
import { Http } from '#angular/http';
import { TrackerService } from './Tracker.service';
import { MenuCollection } from "./MenuCollection";
import { Menu } from "./Menu";
#Component({
moduleId: module.id,
selector: 'tracker-component',
templateUrl: '/public/app/templates/pages/tracker/mysite.tracker.component.html',
styleUrls: ['../../../scss/pages/racker/tracker.css'],
providers: [TrackerService]
})
export class TrackerComponent implements OnInit{
MenuCollection: MenuCollection;
#Output()
overlay: EventEmitter<any> = new EventEmitter();
constructor(private http: Http, private TrackerService: TrackerService) {
let c = confirm("test");
if (c) {
this.onShowOverlay();
}
}
ngOnInit(): void {
this.MenuCollection = new MenuCollection();
this.MenuCollection.activeMenu = new Menu('Active Menu', []);
this.TrackerService.getTrackerData().then(Tracker => {
this.MenuCollection = Tracker;
this.MenuCollection.activeMenu = this.MenuCollection.liveMenu;
console.log(this.MenuCollection);
},
error => {
alert('error');
})
}
onShowOverlay() { //This doesn't seem to 'emit' and trigger my overlay function
this.overlay.emit('test');
}
}
At a high level, all I'm wanting to do is invoke a components function from another component. Thanks in advance for any helpful input
You can use the #ContentChild annotation to accomplish this:
import { Component, ContentChild } from '#angular/core';
class ChildComponent {
// Implementation
}
// this component's template has an instance of ChildComponent
class ParentComponent {
#ContentChild(ChildComponent) child: ChildComponent;
ngAfterContentInit() {
// Do stuff with this.child
}
}
For more examples, check out the #ContentChildren documentation.

Angular 2, How to pass options from parent component to child component?

I have been looking for a solution for this for a while. I have tried a bunch of different things from #Input, #Query, dynamicContentLoader, #Inject, #Inject(forwardRef(() but haven't been able to figure this out yet.
My Example Structure:
parent.ts
import {Component} from 'angular2/core';
#Component({
selector : 'my-app',
directives : [Child],
template : `<parent-component></parent-component>`
})
export class Parent
{
private options:any;
constructor()
{
this.options = {parentThing:true};
}
}
child.ts
import {Component} from 'angular2/core';
#Component({
selector : 'parent-component',
template : `<child-component></child-component>`
})
export class Child
{
constructor(private options:any) <- maybe I can pass them in here somehow?
{
// what I am trying to do is get options from
// the parent component at this point
// but I am not sure how to do this with Angular 2
console.log(options) <- this should come from the parent
// how can I get parent options here?
// {parentThing:true}
}
}
This is my current HTML output in the DOM, so this part is working as expected
<parent-component>
<child-component></child-component>
</parent-component>
Question Summarized:
How can I pass options from a parent component to a child component and have those options available in the child constructor?
Parent to child is the simplest form of all but it's not available in the constructor, only in ngOnInit() (or later).
This only requires an #Input() someField; in the child component and using binding this can be passed from parent to children. Updates in the parent are updated in the child (not the other direction)
#Component({
selector: 'child-component',
template'<div>someValueFromParent: {{someValueFromParent}}</div>'
})
class ChildComponent {
#Input() someValueFromParent:string;
ngOnInit() {
console.log(this.someValue);
}
}
#Component({
selector: 'parent-component',
template: '<child-component [someValueFromParent]="someValue"></child-component>'
})
class ParentComponent {
someValue:string = 'abc';
}
to have it available in the constructor use a shared service. A shared service is injected into the constructor of both components. For injection to work the service needs to be registered in the parent component or above but not in the child. This way both get the same instance.
Set a value in the parent and read it in the client.
#Injectable()
class SharedService {
someValue:string;
}
#Component({
selector: 'child-component',
template: '<div>someValueFromParent: {{someValueFromParent}}</div>'
})
class ChildComponent {
constructor(private sharedService:SharedService) {
this.someValue = sharedService.someValue;
}
someValue:string = 'abc';
}
#Component({
selector: 'parent-component',
providers: [SharedService],
template: '<child-component></child-component>'
})
class ParentComponent {
constructor(private sharedService:SharedService) {
sharedService.someValue = this.someValue;
}
someValue:string = 'abc';
}
update
There is not much difference. For DI only the constructor can be used. If you want something injected it has to be through the constructor. ngOnInit() is called by Angular when additional initialization has taken place (like bindings being processed). For example if you make a network call it doesn't matter if you do it in the constructor on in ngOnInit because the call to the server is scheduled for later anyway (async). When the current sync task is completed, JavaScript looks for the next scheduled task and processes it (and so on). Therefore it's probably so that the server call initiated in the constructor is actually sent after ngOnInit() anyway no matter where you place it.
You could use an #Input parameter:
import {Component,Input} from 'angular2/core';
#Component({
selector : 'parent-component',
template : `<child-component></child-component>`
})
export class Child {
#Input()
options:any;
ngOnInit() {
console.log(this.options);
}
}
Notice that the value of options is available in the ngOnInit and not in the constructor. Have a look at the component lifecycle hooks for more details:
https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
And provides the options as decribed below:
import {Component} from 'angular2/core';
#Component({
selector : 'my-app',
directives : [Child],
template : `<parent-component [options]="options"></parent-component>`
})
export class Parent {
private options:any;
constructor() {
this.options = {parentThing:true};
}
}
If you want to implement custom events: child triggers an event and the parent register to be notified. Use #Output.

Categories

Resources