Raj
Raj

Reputation: 51

Angular OnChanges firing for Input variable, but variable is not updating

This is a pretty simple thing I'm trying to do and I've never ran into this problem before, so hopefully someone can explain what I'm doing wrong here. I have a simple parent-child component relationship here, with an Input variable going into ChildComponent.

For more context, the ChildComponent is a bootstrap modal. Additionally, I have another ChildComponent that uses an Output EventEmitter to send an object that was clicked on to the ParentComponent, to be sent to the modal as the Input.

As for the problem, I have OnChanges implemented, and it detects the change to the Input just fine, I can see this object being sent into the modal component. But, when the modal opens, the Input variable is undefined. And further, when I close the modal, it is still undefined. So, somewhere along the way I am doing something wrong with this. Here is some code to help:

ChildComponent that sends the initial object

alertPopup(alert:Notification) {
  this.notifyAlert.emit(alert);
}

ParentComponent function that takes in object from ChildComponent, and sends it to modal ChildComponent

showPopup(alert:Notification) {
  this.selectedNotification = alert;
  this.$('#alert-modal').modal({backdrop: 'static'});
}

And the html where I put the modal ChildComponent, taking in selectedNotification

<app-alert-popup [notification]="selectedNotification"></app-alert-popup>

Modal ChildComponent code

@Input() notification:Notification;

constructor(private dateService:BusinessDateService) { }

ngOnInit(): void { }

ngOnChanges(changes:SimpleChanges) {
  // here, the changes show appropriately, indicating the Input does in fact change
  console.log(changes);
  // and even further, this also shows the actual variable with the correct value
  console.log(this.notification);
}

close() {
  // here, the console log shows undefined when the modal closes
  console.log(this.notification);
  this.$('#alert-modal').modal('toggle');
}

ack() {
  this.close();
}

So, if I had to guess it is some sort of timing issue, but I'm not sure how to resolve that. I tried adding a sleep of 1 second after the ParentComponent selectedNotification variable changed but that didn't work either. I can provide any additional information as needed, thank you for any help!

Upvotes: 0

Views: 830

Answers (1)

Raj
Raj

Reputation: 51

Well, the answer was not related at all to any of this. I had made a change in the html files where the modal component was put, and Angular change detection never picked up on it, causing the component to be rendered twice. For whatever reason, this was causing the problem.

Upvotes: 1

Related Questions