I have a modalComponent that I create dynamically.
<div class="modal">
<div class="modal-body">
Test
</div>
<div class="modal-footer">
<button (click)="callbackFunction()">success</button>
<button>abort</button>
</div>
</div>
This component has an Input callbackFunction that'a function that I want to invoke from my parent component.
import {
Component,
Input,
OnInit,
QueryList,
ViewChildren
} from "#angular/core";
import { ModalService } from "../modal.service";
#Component({
selector: "app-modal",
templateUrl: "./modal.component.html",
styleUrls: ["./modal.component.css"]
})
export class ModalComponent implements OnInit {
#Input() callbackFunction: () => void;
constructor(private modalService: ModalService) {}
ngOnInit() {}
}
After that I created a service:
import {
ApplicationRef,
ComponentFactoryResolver,
ComponentRef,
Injectable,
Injector
} from "#angular/core";
import { ModalComponent } from "./modal/modal.component";
#Injectable()
export class ModalService {
dialogComponentRef: ComponentRef<ModalComponent>;
open(callbackFunction: any) {
const modalComponentFactory = this.cfResolver.resolveComponentFactory(ModalComponent);
const modalComponent = modalComponentFactory.create(this.injector);
modalComponent.instance.callbackFunction = callbackFunction;
this.dialogComponentRef = modalComponent;
document.body.appendChild(modalComponent.location.nativeElement);
this.appRef.attachView(modalComponent.hostView);
}
close() {
this.appRef.detachView(this.dialogComponentRef.hostView);
}
constructor(
private appRef: ApplicationRef,
private cfResolver: ComponentFactoryResolver,
private injector: Injector
) {}
}
After componentFactoryResolver I pass my function as instance.
In my parent controller I create a function
sayHello(
this.myService.doSomething();
}
and after that I create a function for opening a modal
open(this.sayHello());
When I click on the button and I invoke callback function, "this" is not referred to Parent component but to Modal Component and sayHello is undefined. How can I fix this situation?
I don't want to use emit.
This is my stackblitz: Example
Basically there are three solutions for this: Output + EventEmitter, #ViewChild and Subject
ViewChild solution
This one can be used when the button is defined on the Parent and you want to get something from the Child.
///////parent.component.ts
...
import { ChildComponent } from 'child/child.component';
...
export class ParentComponent {
#ViewChild(ChildComponent) childComponent: ChildComponent;
public buttonClick(): void {
let childResponse = this.childComponent.getValues();//will return '1234'
...
}
}
///////child.component.ts
export class ChildComponent {
valueInsideChild = '1234';
public getValues(): string {
return this.valueInsideChild;
}
}
Output + EventEmitter solution
In this scenario the child itself sends something to the parent(aka the button is inside the child)
implementation on stackblic
//////parent.component.html
<child-selector
($buttonClicked)=clickAction($event)>
</child-selector>
//////parent.component.ts
...
export class ParentComponent {
public clickAction(value: string): void {
console.log(value);//will log 'something1234 when child button is clicked
}
}
//////child.component.ts
...
import { Output, Component, EventEmitter } from '#angular/core';
...
export class ChildComponent {
#Output() $buttonClicked = new EventEmitter<string>();
public click(): void {
this.$buttonClicked.emit('something1234');
}
}
//////child.component.html
<button (click)="click()">
Subject
Interface responses using your modalService+subject+observables
///app.component.ts
...
export class AppComponent {
...
open() {
//subscribe to the observable :)
this.modalService.open(this.sayHello).subscribe(response => {
alert(response.text);
});
}
...
}
///modal.component.html
...
<button (click)="click()">success</button>
...
///modal.component.ts
...
export class ModalComponent {
constructor(private modalService: ModalService) {}
...
public click(): void {
this.modalService.close({text: 'Hello World'});
}
}
///modal.service.ts
...
import { Subject, Observable } from 'rxjs';
...
export class ModalService {
...
private _modalResponse = new Subject<any>();
...
open(): Observable<any> {//this is your open function
...
return this._modalResponse.asObservable();//return an observable where the modal responses will be emitted
}
close(response: any): void {
//receives a value from the modal component when closing
this.appRef.detachView(this.dialogComponenRef.hostView);
this._modalResponse.next(response);//emit the response on the Observable return when open was called
}
}
I suggest you to use an Output and a EventEmitter to call the parent component function from the child component, Angular documentation provides a good example on how to do it.
https://angular.io/guide/inputs-outputs#sending-data-to-a-parent-component
Related
I'm a beginner in Angular. I've been facing this issue with calling a method in a component from a component, which they are not related to. I followed a lot of tutorials on the internet but haven't found the solution.
So the detail is:
There are 2 unrelated components. The first component has a button and if I click that button, the string from the first component should be sent to a function in the second component and in that function It should display the string into the console. But the problem I'm facing here is that the function is called only once before I click and it just displays the value "111" which is the default value. Please help me
First component:
export class FirstComponent implements OnInit{
constructor(location:Location, private renderer : Renderer2, private element : ElementRef, private router: Router, private httpClient: HttpClient, private servic: MainService) {
}
clickMe() {
this.servic.sendMessage("001");
}
}
Second component:
export class SecondComponent implements OnInit {
clickEventSubs:Subscription;
constructor(public servic: MainService, private spinner: NgxSpinnerService, private router: Router){}
this.clickEventSubs = this.servic.receiveMessage().subscribe(message => {
this.toggle(message);
})
public toggle(state: string){
console.log(state);
}
}
Shared service:
#Injectable({
providedIn: 'root'
})
export class MainService {
private message = new BehaviorSubject<string>("111");
sendMessage(mess:string) {
this.message.next(mess);
}
receiveMessage(): Observable<any> {
return this.message.asObservable();
}
}
When relationships between component is Child > Parent -
Share date via #viewChild()
In First Component, Use #ViewChild() and pass second component name as an
argument -
#ViewChild(SecondComponent) secondChildView!: SecondComponent;
Then call the second component's function in the first component's function -
import {ViewChild} from '#angular/core';
export class FirstComponent implements OnInit{
#ViewChild(SecondComponent) secondChildView!: SecondComponent;
constructor() {}
clickMe() {
this.secondChildView.toggle('001');
}
}
Whenever you call clickMe function it will call the toggle function of second component and you will get the value in toggle function from the first component.
export class SecondComponent implements OnInit {
constructor(){}
public toggle(state: string){
console.log(state);
}
}
I defined a property here in my function
evs: string
...
openArticle(url){
this.evs = url
console.log(this.evs)
this.navCtrl.navigateForward('/url-page')
}
And I a trying to pass the value of 'this.evs' to another ts file and use its value but I do not know how to do this. I tried exporting it like this.
export const webpage = this.evs
but this.evs has no value until someone performs the openArticle function ad so I keep getting the error. "Cannot read property 'evs' of undefined"
What i need to do is tranfer the variable to the 'url-page' page and use the value of this.evs only after the openArticle function has bee called. How do I go about this?
As per my understanding you are trying to share data between two components.
So choose one of them as per your requirements.
Parent to Child: Sharing Data via Input().
Child to Parent: Sharing Data via Output() and EventEmitter.
Unrelated Components: Sharing Data with a Service.
This link will be helpful.
If the components have a parent/child relationship, You can share data between them via #Inpput() and #Output() decorators.
Sharing data from Parent to Child using #Input() :
<h3>Parent Component</h3>
<label>Parent Component</label>c
<input type="number" [(ngModel)]='parentValue'/>
<p>Value of child component is: </p>
<app-child [value]='parentValue'></app-child>
And in the child component, the 'parentValue' can be received as :
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
#Input() value: number;
constructor() { }
ngOnInit() {
}
}
Now, in the case of sending data from Child to Parent, we can use an #Output() event emitter. So the parent would have a function to receive the emitted data from child as :
parent-app.component.html
<app-child [value]="parentValue" (childEvent)="childEvent($event)"></app-child>
parent-app.component.ts
childEvent(event) {
console.log(event);
}
And, the child.component.ts would look like :
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
#Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
#Input() PData: number;
#Output() childEvent = new EventEmitter();
constructor() { }
onChange(value) {
this.childEvent.emit(value);
}
ngOnInit() {
}
}
If the components do not have a parent/child relationship, a shared service can be used, say, SharedService which has a BehavioralSubject, that emits value from either component, and the other component can then catch the changed value.
Eg:
import { Injectable } from '#angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";
#Injectable()
export class SharedService {
comp1Val: string;
_comp1ValueBS = new BehaviorSubject<string>('');
comp2Val: string;
_comp2ValueBS = new BehaviorSubject<string>('');
constructor() {
this.comp1Val;
this.comp2Val;
this._comp1ValueBS.next(this.comp1Val);
this._comp2ValueBS.next(this.comp2Val);
}
updateComp1Val(val) {
this.comp1Val = val;
this._comp1ValueBS.next(this.comp1Val);
}
updateComp2Val(val) {
this.comp2Val = val;
this._comp2ValueBS.next(this.comp2Val);
}
And component1 as follows :
import { Injectable } from '#angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";
#Injectable()
export class SharedService {
comp1Val: string;
_comp1ValueBS = new BehaviorSubject<string>('');
comp2Val: string;
_comp2ValueBS = new BehaviorSubject<string>('');
constructor() {
this.comp1Val;
this.comp2Val;
this._comp1ValueBS.next(this.comp1Val);
this._comp2ValueBS.next(this.comp2Val);
}
updateComp1Val(val) {
this.comp1Val = val;
this._comp1ValueBS.next(this.comp1Val);
}
updateComp2Val(val) {
this.comp2Val = val;
this._comp2ValueBS.next(this.comp2Val);
}
Component 2 :
import { Component, AfterContentChecked } from '#angular/core';
import { SharedService } from "../../common/shared.service";
#Component({
selector: 'app-component2',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css']
})
export class Component2Component implements AfterContentChecked {
comp1Val: string;
comp2Val: string;
constructor(private sharedService: SharedService) {
this.sharedService.comp2Val = "Component 2 initial value";
}
ngAfterContentChecked() {
this.comp1Val = this.sharedService.comp1Val;
}
addValue(str) {
this.sharedService.updateComp2Val(str);
}
}
You can find more on different types of subjects here
I have the following scenario in my Angular app:
A component MainDashboardComponent that is visible when I have the route /. Obviously I have the <router-outlet> tag in my app.component.html file, which looks like this:
<app-side-menu></app-side-menu>
<div class="main-container">
<div class="content">
<router-outlet></router-outlet>
</div>
</div>
As you can see I have a SideMenuComponent I use to have a side menu on all my routes. In MainDashboardComponent I have a method that for some reason needs to toggle a chat element that is situated on the side menu.
Inside the SideMenuComponent I have a method that handles the visibility toggle for the chat element and it works as expected. How can I call this method from my MainDashboardComponent and toggle the chat element from there?
What I tried with no success
I tried to inject the SideMenuComponent inside my MainDashboardComponent but, though the method toggleChat() is called, the element doesn't change it's visibility. Looks like I have a kind of multiple instance of the same component I guess...
Can you please help me with this? Thank you!
MainDashboardComponent
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-main-dashboard',
templateUrl: './main-dashboard.component.html',
styleUrls: ['./main-dashboard.component.scss']
})
export class MainDashboardComponent implements OnInit {
constructor() { }
ngOnInit() {}
setFocus(id) {
// here I'd like to call SideMenuComponent togglechat() ...
}
}
SideMenuComponent
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-side-menu',
templateUrl: './side-menu.component.html',
styleUrls: ['./side-menu.component.scss']
})
export class SideMenuComponent implements OnInit {
showChat: boolean;
constructor() {
this.showChat = false;
}
ngOnInit() {
}
toggleChat() {
this.showChat = !this.showChat;
}
}
To communicate between different components, there are different ways.
If you want to communicate between parent and child component, you can use EventEmitter to emit event from child component and handle the event in your parent component
If you want to communicate between any components, you can use Service and implement communication with the help of EventEmitter or Subject/BehaviorSubject
In your case, we can create a service, myService.ts and declare and eventEmitter
.service.ts
#Injectable()
export class AppCommonService {
toggle : EventEmitter<boolean> = new EventEmitter<boolean>()
}
mainDashboard.component.ts
constructor(private myService : myService){}
chatStatus : boolean = false;
ngOnInit(){
this.myService.toggle.subscribe(status=>this.chatStatus = status);
}
toggleChat(){
this.myService.toggle.emit(!this.chatStatus);
}
sideMenu.component.ts
constructor(private myService : myService){}
chatStatus : boolean = false;
ngOnInit(){
this.myService.toggle.subscribe(status=>this.chatStatus = status);
}
Generally this is the domain of a service!
Just create a service and add the "showCat" property.
Inject the service into both components
Alter SideMenuComponent to:
toggleChat() {
this.myService.showChat = !this.myService.showChat;
}
Alter MainDashboardComponent, also use this.myService.showChat to show / hide your chat window
Service TS
#Injectable()
export class MyService{
showCat:boolean = true
}
MainDashboardComponent
toggleChat() {
this.myService.showChat = !this.myService.showChat;
}
SideMenuComponent
chatVisiblity = this.myService.showCat //<-- bind this to the element attribute
You could efficiently use child to parent communication in this scenario. You'll need to create a custom event using angular's EventEmitter in your SideMenuComponent and use it in your MainDashboardComponent.
So, here is some code that may help you -
// SideMenuComponent
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-side-menu',
templateUrl: './side-menu.component.html',
styleUrls: ['./side-menu.component.scss']
})
export class SideMenuComponent implements OnInit {
#Output() valueChange = new EventEmitter();
showChat: boolean;
constructor() {
this.showChat = false;
}
ngOnInit() {
}
toggleChat() {
this.showChat = !this.showChat;
this.valueChange.emit(this.showChat);
}
}
// MainDashboardComponent
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-main-dashboard',
template: `<app-side-menu (valueChange)='setFocus($event)'></app-side-menu>`
styleUrls: ['./main-dashboard.component.scss']
})
export class MainDashboardComponent implements OnInit {
constructor() { }
ngOnInit() { }
setFocus(event) {
// check for required input value
console.log(event);
}
}
Refer these tutorials if required -
https://dzone.com/articles/understanding-output-and-eventemitter-in-angular,
https://angular-2-training-book.rangle.io/handout/components/app_structure/responding_to_component_events.html
I want to call a function with an argument when an element is loaded.
Just like nginit in angualrjs. Can we do it in Angular 4 and above?
<div *ngFor="let item of questionnaireList"
(onload)="doSomething(item.id)" >
</div>
My Typescript function:
doSomething(id) {
console.log(id);
}
You need to write a directive
import {Directive, Input, Output, EventEmitter} from '#angular/core';
#Directive({
selector: '[ngInit]'
})
export class NgInitDirective {
#Input() isLast: boolean;
#Output('ngInit') initEvent: EventEmitter<any> = new EventEmitter();
ngOnInit() {
if (this.isLast) {
setTimeout(() => this.initEvent.emit(), 10);
}
}
}
Using in html
<div *ngFor="let quetionnaireData of questionnairelist ; let $last = last" [isLast]='$last'
(ngInit)="doSomething('Hello')"></div>
Also you declare your directive in app.module
#NgModule({
declarations: [
..
NgInitDirective
],
......
})
Use ngOnInit() and the #Input directive.
For example, in your child component:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'my-component',
template: `
<h3>My id is: {{itemId}}</h3>
`
})
export class MyComponent implements OnInit
{
#Input() itemId: string;
//other code emitted for clarity
public ngOnInit(): void
{
// Now you can access to the itemId field e do what you need
console.log(this.itemId);
}
}
In your parent component
<div *ngFor="let item of questionnairelist">
<my-component itemId='{{item.Id}}'></my-component>
</div>
Your Function:
ExecuteMyFunction(value:any):void{
console.log(value);
}
If you wants to pass parameter which declared in component itself and set from component then try as below:
notificationMessage:string='';
#Input() message:string;
ngAfterViewInit(){
this.ExecuteMyFunction(this.notificationMessage);
}
If you set variable as Input parameter and set from other component then try as below: ngOnChanges will fire every time when your Input variable value is changed.
import { Component, OnChanges, Input } from '#angular/core';
ngOnChanges(changes: any) {
if (changes.message != null && changes.message.currentValue != null) {
this.ExecuteMyFunction(this.message);
}
}
HTML:
<ng-container *ngFor="let item of items">
<div *ngIf="doSomething(item.id)"></div>
</ng-container>
TS:
doSomething(value){
//logic
return true;
}
import { Router,NavigationEnd } from '#angular/router';
constructor( private router: Router ) {
this.router.events.subscribe((e) => {
if (e instanceof NavigationEnd) {
// Function you want to call here
}
});
}
I'm using a third-party library that requires me to implement my own event listener. This is done by implementing window.onGoogleYoloLoad = function() { ... }. I tried to implement it like this in my user service file:
#Injectable()
export class UserService {
public userCredentials = new EventEmitter<Credentials>();
constructor(){
window.onGoogleYoloLoad = function(credentials){
this.userCredentials.emit(credentials);
}
}
}
Then I subscribed to the event. The subscribers do get notified, but the view does not get updated. It's like angular doesn't know the event happened.
The callback is running outside the Angular zone. Move the callback to a component and call ChangeDetectorRef.detectChanges
import { Component, ChangeDetectorRef } from '#angular/core';
#Component(...)
export class MyComponent {
public userCredentials = new EventEmitter<Credentials>();
constructor(
private cd: ChangeDetectorRef,
private userService: UserService
){
window.onGoogleYoloLoad = function(credentials){
this.userService.userCredentials.emit(credentials);
this.cd.detectChanges();
}
}
}
Re-entering the Angular zone is another option: What's the difference between markForCheck() and detectChanges()
import { Injectable, NgZone } from '#angular/core';
#Injectable()
export class UserService {
public userCredentials = new EventEmitter<Credentials>();
constructor(private zone: NgZone){
window.onGoogleYoloLoad = function(credentials){
this.zone.run(() => {
this.userCredentials.emit(credentials);
})
}
}
}