Angular: How to send string values to another component using EventEmitter? - html

I have a parent component and a child component, I want to send 2 values from the child component via EventEmitter to the parent component as I want to use the printMessages() function there.
I have a click event on the child component which emits 2 string values, but I'm unsure how to connect the emit event to the parent component and for the printMessages() function to run. How can the parent component read these values into the "printMessages()" function and for that function to run after the values have reached it? As you can see, I currently have no HTML in the parent component, perhaps I need to do something there?
Parent Component:
import { Component } from '#angular/core';
#Component({
selector: 'parent-component',
template: ``,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
// Function in which I want to send values from the child component.
printMessages(string1: string, string2: string) {
console.log(string1, string2);
}
Child Component:
import { Component, Output, EventEmitter } from '#angular/core';
#Component({
selector: 'child-component',
template: `
<button (click)="sendStrings()">Send Strings</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
#Output() message = new EventEmitter();
constructor() { }
sendStrings(){
this.message.emit({string1:"Hello", string2:"World!"});
}
}

You need to react on the child components event within the template and call the method.
import { Component } from '#angular/core';
#Component({
selector: 'parent-component',
template: `<child-component (onMessage)="printMessages(e)"></child-component>`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
printMessages(event) {
// strings are included in event object
}
}

Related

Component Interaction #Input

I would like a component to send input to another component. Below is the code .ts and .html. of the two components.
Now the problem is that the html page of the parent component also shows the html part of the child component ... I want the component to pass only one string to the child component
Parent.ts
import ...
#Component({
selector: 'app-parent',
templateUrl: './parent.html',
styleUrls: ['./parent.css']
})
export class ParentComponent implements OnInit {
sostegno : string;
constructor() { }
ngOnInit() { }
avvia1() {
this.sostegno = "xxx";
this.router.navigate(['./xxx'], { relativeTo: this.route });
}
avvia2()
this.sostegno = "yyy";
this.router.navigate(['./yyy'], { relativeTo: this.route });
}
}
Parent.html
<div>
...
</div>
<app-child [sostegno]="sostegno"></app-child>
Child.ts
import ...
#Component({
selector: 'app-child',
templateUrl: './child.html',
styleUrls: ['./child.css']
})
export class ChildComponent implements OnInit {
#Input() sostegno : string;
constructor() { }
ngOnInit() {
console.log(this.sostegno);
}
}
There are some changes which you need to make because looking at the code which your currently have it seems incomplete.
You are using this.router without injecting the Router class in your constructor.
You are using this.route without injecting the ActivatedRoute class in your constructor.
To test that your parent > child interaction is working you can remove your param and instead place a test for the html
<app-child [sostegno]="'Test'"></app-child>
This should work for your ngOnInit function which is inside of your child component. If this works all you need to do now is either initialize sostegno in your parent component else your console log inside your child component will not reflect the changes when you call avvia1 or avvia2 inside of your parent class.
Hope this helps!

Calling a function between components

I have two components(comp1 and comp2). I am trying to call a function which is inside comp1 from comp2 and it is not happening and it is throwing an error. But it is successful when calling a function inside comp2 from comp1.
I want it to happen in both the ways
(i.e)
(a) function trigger from comp2 inside comp1
(b)function trigger from comp1 inside comp2
I have attached the sample code.
https://stackblitz.com/edit/angular-jxfzqb
The error is throwing from constructor function on comp1, it cant generate a new instance of comp2.
Please try not use provides of components between components, i suggest you make getting binding components from app.component to comp1 and comp2, example:
app.component.html
<app-comp1 #comp1 [Comp2Component]="comp2"></app-comp1>
<app-comp2 #comp2 [Comp1Component]="comp1"></app-comp2>
app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Comp1Component } from './comp1/comp1.component';
import { Comp2Component } from './comp1/comp2/comp2.component';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
// Get component with attr #comp1
#ViewChild('comp1') comp1: Comp1Component;
// Get component with attr #comp2
#ViewChild('comp2') comp2: Comp2Component;
}
comp1.component.ts
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {
#Input() Comp2Component: Comp2Component;
constructor() { }
ngOnInit() {
}
funcInComp1() {
console.log("comp1 function triggered from comp2");
}
triggerComp2Function() {
this.Comp2Component.funcInComp2();
}
}
comp2.component.ts
import { Input, Component, OnInit } from '#angular/core';
import { Comp1Component } from '../comp1.component';
#Component({
selector: 'app-comp2',
templateUrl: './comp2.component.html',
styleUrls: ['./comp2.component.css']
})
export class Comp2Component implements OnInit {
#Input() Comp1Component: Comp1Component
constructor() { }
ngOnInit() {
}
triggerComp1Function() {
this.Comp1Component.funcInComp1();
}
funcInComp2() {
console.log("comp2 function triggered from comp1");
}
}
stackblitz:
https://stackblitz.com/edit/angular-itmzhe

Angular html nesting

Let's say I have in some upper level class some angular template code that looks like this
<outer-component>
<a></a>
</outer-component>
Where <a> can be any module that extends a certain interface defined elsewhere, is there a way for <outer-component> be able to take <a> or whatever is placed inside the tags and communicate with it specifically be able to listen to functions or bind to variables in a way that is as succinct as the snippet above?
If you want to share data between a parent and a child (hierarchical relationship) you can use EventEmitter to allow the parent to get data from the child.
In the child component:
import { Component, Input, Output, EventEmitter } from 'angular/core';
#Component({
selector: 'app-child',
template: `
<h3>Child</h3>
Say {{message}}
<button (click)="sendMessage()"></button>
ยด,
styleUrls: ['pathToStyles.css']
})
export class ChildComponent {
message: string = "Hello world";
#Output() messageEvent = new EventEmitter<string>();
constructor() {}
sendMessage() {
this.messageEvent.emit(this.message);
}
}
In the parent component:
import { Component } from '#angular/core';
#Component({
selector: 'app-parent',
template: `
Message: {{message}}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['pathToStyles.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}

Angular 2/4: Can't update child component view

I want to update the value of str which I used in the view of child component from the parent component, by calling the function change() of child component
here is my code.
import { Component } from '#angular/core';
import { ChildComponent } from './child/child.component';
#Component({
selector: 'app-root',
template: `
<h1>parent</h1>
<button (click)="changeChild()">change child</button>
<app-child></app-child>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private cc:ChildComponent) {}
changeChild(){
this.cc.change();
}
}
and the child component is:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-child',
template: `
<p>{{str}}</p>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
private str;
constructor() {
this.str = 'initial'
}
change(){
this.str = 'changed'
}
ngOnInit() {
}
}
but the value str in the view never updated to "changed".
please Any help because I am new in Angular 4 ??
Use #ViewChild to get reference of child component
in Parent component
import {ChildComponent} from 'child.component.ts'
export class ParentComponent{
------
#ViewChild(ChildComponent)
private child:ChildComponent
---
changeChild(){
this.child.change()
}
}

how can i pass value from child to parent component in angular 2?

I need to get data from child component. My child component has form which is in popu. How can i pass full details to parent component.
my parent component ts file is
import { Component, OnInit } from '#angular/core';
import {MdDialog, MdDialogRef} from '#angular/material';
#Component({
selector: 'app-vehicle-relocate',
templateUrl: './vehicle-relocate.component.html',
styleUrls: ['./vehicle-relocate.component.css'],
})
export class VehicleRelocateComponent implements OnInit {
lat: number = 11.074529;
lng: number = 78.003917;
zoom: number = 14;
ngOnInit() {
}
selectedOption: string;
constructor(public dialog: MdDialog) {}
openDialog() {
let dialogRef = this.dialog.open();
dialogRef.afterClosed().subscribe(result => {
this.selectedOption = result;
});
}
}
My child component is in parent component
import { Component, OnInit, Input } from '#angular/core';
import {MdDialog, MdDialogRef} from '#angular/material';
#Component({
selector: 'app-relocate-form',
templateUrl: './relocate-form.component.html',
styleUrls: ['./relocate-form.component.css']
})
export class RelocateFormComponent implements OnInit {
constructor(public dialogRef: MdDialogRef<RelocateFormComponent>) {}
#Input() title:string;
ngOnInit() {
}
}
You can add an Output to your child component.
For example: #Output() notifySubmit : EventEmitter<any> = new EventEmitter<any>()(you can put whatever type you want if you don't want 'any').
Then when you're submitting the form in your child component, you have to notify the parent with the Output:
this.notifySubmit.emit(myValues)
Now you have to receive the event in the parent component. When you call your RelocateFormComponent from VehicleRelocateComponent you need to pass a function to the Output.
<app-relocate-form (notifySubmit)="myFunction($event)" ... ></app-relocate-form>
myFunction($event)has to be in the parent component. The $event parameter equals to what you sent with this.notifySubmit.emit(myValues).