Passing Data onChange from child to parent? Angular - javascript

I need to passing data from child to parent but on change.
Child component code:
<input type="file" name="file" accept="image/*"
(change)="handleInputChange($event)">
Parent component:
<app-file-uploader></app-file-uploader> //this is child component
I need pass ($event) to parent component.

You need to use Angular's Output() directive. This is how it's done:
First: In your child component, add the following import statement:
import { Output } from '#angular/core';
Second: In the child component class: add the following property:
#Output() onChange = new EventEmitter<any>();
Now in your handleInputChange($event), you need to emit the onChange property:
handleInputChange($event){
// ... all of your logic
this.onChange.emit($event); // this will pass the $event object to the parent component.
}
Finally: In your parent component template, you can call your component like this:
<app-file-uploader (onChange)="callSomeFunction($event)"></app-file-uploader>
Note: replace callSomeFunction with whatever function you're calling.
Here's the Angular Documentation on how to use Output(). Hope this answer helps you!

Related

how to pass dynamic data from parent to child in angular2+

As we know , in angular parent to child communication happened using #Input decorator but how to pass dynamic data from parent to child.for example 'name' property is defined in parent and it's value changes dynamically and updated value of 'name' we are going to using in child component so how to achieve it without services.
you can watch your input changes in the child component with ngOnChanges lifecycle
in your child component you should implements OnChanges
ngOnChanges(changes: SimpleChanges): void {
for (let propName in changes) {
let change = changes[propName];
if (propName === "YOUR_INPUT_NAME") {
this.YOUR_INPUT_NAME = (change.currentValue);
}
}
}
You can make the use of service to get the updated value in child when it gets changed in parent.
For that you need to declare the variable in the service of type observable.
your myService.service.ts would be having the following code:
#Injectable()
export class myService {
myInput:BehaviorSubject<boolean> = new BehaviorSubject(false)
}
now from your parent component change the value of this myInput by using:
myServie.myInput.next(true)
and subscribe this variable in your child component by using:
myService.myInput.subscribe((data)=>{console.log(data)})
In both the parent and child component add the line private mySerivce:MyService in the arguments of constructor.

Vue.js Passing variable from Parent to child component

Parent component: ShowComment
Child component: EditComment
I'm trying to pass the value of this.CommentRecID to the child component.
I wrote this in the template of ShowComment:
<EditComment CommentRecID="this.CommentRecID" v-if="showEdit"></EditComment>
and
this.showEdit = true;
but the value of this.CommentRecID is shown as undefined in the child component:
I thought that writing props: ["CommentRecID"], in the child component would have already been enough to pass the data, but it wasn't (because it's related to jQuery I think).
What is wrong with the way I try to pass the values?
Here's the parent component.
Here's the child component.
You shouldn't need to use this in VueJS directives. Also, instead of using a static attribute, you need to use v-bind:
<EditComment v-bind:comment-rec-id="commentRecId" v-if="showEdit"></EditComment>
Also, there's an issue with the casing: for VueJS, in template props should be kebab-cased, while in the component JS logic you should use camelCase props. Remember to update your child component's prop declaration so that it can read the new prop correctly:
props: ["commentRecId"]
You need to use VueJS binding
<EditComment :comment-rec-id="CommentRecID" v-if="showEdit"></EditComment>
props: ['commentRecId']

Why angular2 one-way binding between components works wrong with objects?

I have parent and child components.
I want to send form's values from parent to child component.
Child component can do everything with this data, but all changes are local and should not be returned back to parent component.
When i send a simple variable to child comp – everything works fine and changes doesn't returned back to parent.
But when i send form's values – all changes returns back to parent component...
Live
https://stackblitz.com/edit/angular-dvqyjr
Parent Component JS
export class AppComponent {
constructor (private formBuilder: FormBuilder){};
simpleVariable = 'Value';
form: FormGroup = this.formBuilder.group({
id: 1,
name: 'Name'
});
Parent Component HTML
<hello [simpleVariable]="simpleVariable" [form]="form.value"></hello>
Child Component JS
export class HelloComponent {
#Input() simpleVariable;
#Input() form;
}
Child Component HTML
<input [(ngModel)]="simpleVariable">
<input [(ngModel)]="form.name">
Question
So how can i send an object to child component and modify it without returning data to parent?
This is quite simple. The reason for this behavior is that the form.value is an object. Meaning that you're sharing a reference object with parent and child. Meaning that any change to this object will result in a change in both parent and child.
In order to make changes in child that won't affect your parent, create a deep copy of your object using Object.assign function and use it in your child component.
export class HelloComponent implements OnInit {
_from: {};
#Input() simpleVariable;
#Input() form;
ngOnInit() {
this._form = {};
Object.assign(this._from, this.form);
}
}
Forked and edited example
From the Angular documentation at Reactive Forms - Step 2: Associating the FormGroup model and view:
A form group tracks the status and changes for each of its controls, so if one of the controls changes, the parent control also emits a new status or value change.
You can try the following one with the form:
<form [formGroup]="form">
<input formControlName="name">
</form>
It all comes to Explaining Value vs. Reference in Javascript as well as Angular's Change Detection
Overall, #benshabatnoam already answered you'r question - in order to execute change detection - you need to change object reference, either by old fashioned way:
Object.assign(this._from, this.form);
Or ES6 way:
this._from = {...this.form}

emit event with arguments from child to parent with ember 3.6

I would like emit one event from child to parent but with some argument.
Child component javascript
import Component from '#ember/component';
export default Component.extend({
tagName: 'li',
actions: {
favoriteWasClicked() {
const organization = this.get('organization');
// organization.id value equal to 'facebook' here in my app
// we're gonna send its id to parent component "orgs" like an argument of clicked method
this.clicked(organization);
}
}
});
Parent component .hbs template
{{child-component
clicked=(action "favoriteClicked" value="organization.id")
}}
Parent component javascript controller file
import Controller from '#ember/controller';
export default Controller.extend({
actions: {
favoriteClicked(orgId) {
console.log(orgId);
}
}
});
I'm getting undefined in console.log(orgId); Why? What am i missing
Thank you!
You simply need to change organization.id to just id. What I mean is; you need to do the following:
{{child-component
clicked=(action "favoriteClicked" value="id")
}}
You send the event from the child component with an organization; which simply contains an id; but not organization.id; so it must be just id for the value property in the action passing within parent's template.
I prepared an ember twiddle for you to illustrate the solution I proposed in action. Hope that helps.

How to use multiple copies of same child tag having Event Emitter in it at the same time.

I am having a child component which emits data through event emitter.The Emitting data is bind with ngModel in parent. And the emitting method in it is called from parent component.
I have created child component because i am having two same form. So i created a single form component and used it twice and binded with their data.
//Child Component Code
import {Component, EventEmitter, Input, Output} from 'angular2/core'
#Component({
selector: 'child-component',
template: `
<input [ngModel]="formObj.title" >
`
})
export class ChildComponent {
#Input() formObject: Object;
#Output() formObjectChange= new EventEmitter();
emitChangeforParent() {
this.formObjectChange.emit(newValue);
}
}
//Parent Component
#Component({
selector: 'parent-component',
template: `
<child-component[(formObject)]="doseObject1" #firstForm></child-component>
<child-component[(formObject)]="doseObject2" #secondForm></child-component>
<button (click)="save()">Save</button>
`
})
export class ParentComponent {
doseObject1 ={title:''};
doseObject2 ={title:''};
save(){
this.firstForm.emitChangeforParent();
this.secondForm.emitChangeforParent();
console.log(this.doseObject1); //Updated data by child is available.But this works when i used single tag.
But when i use multiple child tag it does not work
}
}
Problem is that whenever I use single form tag it works fine. The update done by child is reflected here in parent.
But when i use same tag tag twice, than on calling its child emitChangeForParent() method does not work.
I think you might be a little confused about how emitChangeForParent should work. This kinda of method would usually be called by the child, and used by the parent.
so the child component would have (change)="emitChangeForParent() , then on the parent you you would have
basically this means whenever the child component calls emit, it passes the data up, and the parent component can catch it by having a callback.
However, In this case I dont think you need to do that. This is most useful for value types like numbers. If you are passing in an refence type, like your json object doseObject1 ={title:''}, the parent object should still have an up to date reference to it.
I think all you need to do to make this work is have you child component template be "" with the banana in the box double binding syntax. Then the parent will still always have an accurate value of doseObject1.title and doseObject2.title
There is no need to emit the data. The double binding syntax returns the changes done in child component to parent component.

Categories

Resources