I'm working on small Angular project, and I want to pass value from parent to child after it is addedd to the list, so it goes like this:
new-component
emits item to the list-component
and after it's addedd to the list, lets move it forward to view-component
, so I can see recently addedd item in case I want to edit something--
And everything works fine until I want to see it on view-component
(it's successfully added to the list etc.) here is my code:
on a new component item is emitted to list:
onSubmit() {
this._viewService.save(this.view)
.subscribe(
(data: View) => {
this.onSave.emit(data);
}
}
As list is parent list is listening for this emitter.
<view-new #addNew (onSave)="onAdd($event)"></view-new>
After it is emitted, its available in onAdd
method, and until this part everything is ok:
onAdd(view: View) {
this.receivedView = view;
// And here I'm opening viewDisplay compnent which displaying info about recently addedd data
this.viewDisplay.show();
}
Also on my list which is parent component is also included display component, which needs to display info about recently addedd item:
<view-display #displayView [view]="receivedView"></view-display>
And when I open this component by calling this.viewDisplay.show();
@Input() view: View;
Which is part of display component is allwayas empty :
show() {
$('#' + this.id).modal('show');
console.log("added - selected:view", this.view);
}
this.view
which should be filled onAdd method from parent and passed here is allways empty.. I dont know how..
Thanks guys
Cheers
Angular needs to know that the value of view has changed. You usually do this by defining a setter . By defining a setter, changes to an input variable can be tracked. You also need to define a private property to save the value in.
private _view: any;
@Input()
get view(): any) {
return this._view;
}
set view(view: any) {
this._view= view;
// Do other stuff when "view" was updated
}
You can also handle the communiation via the service pattern .
you are updating field recievedView
in a parent, which is bound to view
field in a child. This binding is done by angular change detection mechanism. In your onAdd method you are trying to call viewDisplay.show()
method synchroniously, before the change detection is done, and, because of this field is not updated yet. The simplest solution would be to assign the field of a child in place like
onAdd(view: View) {
this.receivedView = this.viewDisplay = view;
this.viewDisplay.show();
}
but there are surely better options which depend on your project
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.