Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular setter not called with same value

I have a very simple form (with three fields) which updates a configuration. When I click the update button I want a success message to be shown and disappear after 5 seconds. Once submit button is clicked (configuration updated), if the form is submitted again before the previous message has disappeared, I want the previous 5 seconds to be ignored and success message stays for the following 5 seconds.

I tried to achieve that by:

<div *ngIf="message">
  {{ message }}
</div>

And:

_message: string;
_timeout: number;

get message() {
  return this._message;
}

@Input()
set message(value: string) {
  if (value) {
    if (this._timeout) {
      clearTimeout(this._timeout);
    }
    this._timeout = setTimeout(function() {
      this.message = null;
    }.bind(this), 5000);
  }
  this._message = value;
}

I am setting a message once the submit button is clicked. So the message does show and disappear after 5 seconds. But the set method is not called when I try to update the configuration again because the message is always the same - "Success". Any idea how to achieve this?

like image 638
Christina Avatar asked May 17 '26 01:05

Christina


1 Answers

The problem is linked to Angular Change Detection mechanism. On the second submit, if there are no changes, the form is stil marked as pristine and the submit has no effect.

A solution is to add a click listener which explictly call a function to set the message.

<input type="submit" (click)="displayMessage()" />
like image 129
JeRivals Avatar answered May 19 '26 17:05

JeRivals



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!