how to emit multiple events from child to parent component in Angular? - javascript

I am tring in this way but it is listening for first one not for second.
child component
import { Component, EventEmitter, Input, OnInit, Output } from '#angular/core';
#Output() userAdded: EventEmitter<any> = new EventEmitter();
#Output() userDeleted: EventEmitter<any> = new EventEmitter();
export class ChildComponent{
allUsers = [];
prop = "the value";
addUser(){
this.allUsers.push('john');
this.userAdded.emit(prop);
}
deleteUser(idx) {
this.allUsers.splice(idx, 1);
this.userDeleted.emit(idx);
}
}
parent component
<app-child (userAdded)=onAddUser($event) (userDeleted)=onDeleteUser($event)></app-child>

Parent Component
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
onAddUser(event) {
console.log(event);
}
onDeleteUser(event) {
console.log(event);
}
}
Please follow the link:
StackBlitz Demo

Related

Angular component comuniaction

I need help about angular component comunication.
I have Parent component and children.
In parent component i have list. I would like to click of item list and move data {name, text} to children component and set it to children component where is froala editor.
In Angular, there are two ways you can do implement component intercommunication.
Pass data from parent to child with input binding
#Component({
selector: 'app-parent',
template: `
<app-child [childMessage]="parentMessage"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
parentMessage = "message from parent"
constructor() { }
}
#Component({
selector: 'app-child',
template: `
Say {{ message }}
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
#Input() childMessage: string;
constructor() { }
}
Using Angular Services(This method is used when the components communicating are directly related ). But from you are describing you can do it better with angular service. When you click the item list, you can call the function of services that pushes the data to the BehaviourSubject. After that, all the component that are subscribed to that Behaviour subject will get the data you passed.
#Injectable()
export class DataService {
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
}
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)
}
}
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")
}
}

Angular eventemitter not working when emitting the event from directive

appcomp.html
`<app-child (callemit) = parentFunc($event)> </app-child>`
appcomp.ts
`
import { Component, OnInit, EventEmitter } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.comp.html'
})
export class AppComponent {
ngOnInit() {}
parentFunc(event){
console.log(event)
}
}
`
childcomp.html
childcomp.ts
`
#Component({
selector: 'app-child',
templateUrl: './app.child.component.html'
})
`
mydirective.ts
`
import { Directive, ElementRef, Input, Output, HostListener, EventEmitter } from '#angular/core';
#Directive({
selector: '[myDirective]'
})
export class myAppDirective {
constructor() {}
#Input ('myDirective') val: string;
#Output() callEmit = new EventEmitter();
#HostListener('click')
onClick() {
event.preventDefault();
this.callEmit.emit({event , val});
}
}
`
In the above code i am trying to call parentFunc from appcomp using eventemitter and not able to get this work. Please let me know what is wrong here.
I think you most call callEmit on child component
childcomp.html
and in child Component emit the CallEmit Which called from appComp
childcomp.ts
#Output() callEmit = new EventEmitter();
childFunc(){
this.callEmit.emit();
}
and finally use
appCom.html
`<app-child (callemit) = parentFunc($event)> </app-child>`
appcom.ts
parentFunc(event){
console.log(event)
}
https://stackblitz.com/edit/angular-exxhms
Try it on component

#Output childEvent not initialized

I am fairly new to the Angular world and working on angular 7, I am doing some examples where components share data within, The Parent to child part working fine but when i am trying to send any values from child to parent it's not working.
It shows me this error
app-component.html
<div>{{show}}</div>
<app-communicating-components [Parent]="message" (childEvent)="getMessage($event)"></app-communicating-components>
app-component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'AngularLesson2';
public message = 'Hello my child, Parents here';
public show: string;
getMessage($event) {
this.show = $event;
}
}
communicating-components.component.html
<p>
{{Parent}}
</p>
<button (click)="fireEvent()">Fire from child</button>
communicating-components.component.ts
import { Component, OnInit, Input, Output } from '#angular/core';
import { EventEmitter } from 'events';
#Component({
selector: 'app-communicating-components',
templateUrl: './communicating-components.component.html',
styleUrls: ['./communicating-components.component.css']
})
export class CommunicatingComponentsComponent implements OnInit {
#Input() Parent;
#Output() public childEvent = new EventEmitter();
constructor() {
}
ngOnInit() {
}
fireEvent() {
this.childEvent.emit('Hi, I am child');
console.log("event fire" + this.childEvent);
}
}
What am I doing wrong here?
I believe the problem is in your import import { EventEmitter } from 'events'; is not the one you should import here. Try changing the import to import { EventEmitter } from '#angular/core';
UPDATE
Here's a stackblitz example showing that it works
With Angular newer versions, like 8 you have to:
Import correctly Emitter as k.s. said:
import { EventEmitter } from '#angular/core'
Initialize the emitter for Output:
#Output()
emisor = new EventEmitter<type>();

ExpressionChangedAfterItHasBeenCheckedError . Angular 2(5) *ngIf

I'm using a service to pass data between child and parent with the purpose being to update the parent ui with child specific info depending on what child is loaded.
Service:
import { Subject } from "rxjs/Subject";
export class ChildDataService {
private childDetails = new Subject<{}>();
childLoaded$ = this.childDetails.asObservable();
changedComponentName(option: {}){
this.childDetails.next(option);
}
}
Parent Component:
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { ChildDataService } from "../core/helpers/child-data.service";
import { Subscription } from "rxjs/Subscription";
#Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
childDetails: {title?: string};
private subscription:Subscription;
constructor( private childDataService: ChildDataService) {
this.childDataService.childLoaded$.subscribe(
newChildDetails => {
console.log(newChildDetails);
this.childDetails = newChildDetails
});
}
}
Example Child Component:
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { ChildDataService } from "../../core/helpers/child-data.service";
#Component({
selector: 'app-child-dashboard',
templateUrl: './child-dashboard.component.html',
styleUrls: ['./child-dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ChildDashboardComponent implements OnInit {
constructor(private childDataService: ChildDataService) { }
public ngOnInit() {
this.childDataService.changedComponentName({
title: 'Dashboard'
});
}
}
Parent HTML:
<div class="subheader">
<h1>{{ childDetails?.title }}</h1>
<button *ngIf="childDetails?.title == 'Dashboard'">dashboard</button>
<button *ngIf="childDetails?.title == 'SecondChild'">Second Child</button>
</div>
With this setup I am getting the error "ExpressionChangedAfterItHasBeenCheckedError" when i click on a routerLink, now if i click on the same link a second time, the error persists but the correct button becomes visible. Spent all weekend getting nowhere with this, so any help would be greatly appreciated.
public ngOnInit() {
setTimeout(() => {
this.childDataService.changedComponentName({
title: 'Dashboard'
}), {});
}
it should work.
async ngOnInit() {
await this.childDataService.changedComponentName({
title: 'Dashboard'
});
}

angular 2 output and eventemitter doesn't emit

i'm learning angular 2, and i follow this tutorial: https://egghead.io/lessons/angular-2-angular-2-building-a-toggle-button-component
but the whole part of the output and eventemitter doesn't work.
i do not get any errors and i can't figure out why it doesn't work.
this is my code for the togglelink component:
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
#Component({
moduleId: module.id,
selector: 'app-togglelink',
templateUrl: 'togglelink.component.html',
styleUrls: ['togglelink.component.css']
})
export class TogglelinkComponent implements OnInit {
#Input() state:boolean = true;
#Output() onChange = new EventEmitter();
onClick(){
this.state = !this.state;
this.onChange.emit(this.state);
}
constructor() {}
ngOnInit() {
}
}
and this is the code for the firstpage component that uses the togglelink component:
import { Component, OnInit } from '#angular/core';
import {TogglelinkComponent} from '../togglelink/togglelink.component';
#Component({
moduleId: module.id,
selector: 'app-firstpage',
templateUrl: 'firstpage.component.html',
styleUrls: ['firstpage.component.css'],
directives: [TogglelinkComponent]
})
export class FirstpageComponent implements OnInit {
thetogglestate:boolean = false;
firsttitle = "the first title";
constructor() {}
ngOnInit() {
}
}
and this is the code for the template of the firstpage component:
{{thetogglestate ? 'On' : 'Off'}}
</p>
<h2 *ngIf="thetogglestate">
{{firsttitle}}
</h2>
<p>
firstpage works!
</p>
when i change manually thetogglestate it does work, so i understand that the issue is with the output and the eventemitter part.
any idea why?
best regards
In the firstpage.component.html template, you need to register some processing for this event to toggle the value of the thetogglestate variable.
Something like that:
<app-togglelink (onChange)="thetogglestate = !thetogglestate"></app-togglelink>

Categories