Reputation: 411
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?
Upvotes: 3
Views: 2185
Reputation: 264
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()" />
Upvotes: 2
Reputation: 109
Please check this code. I'm not sure about checking cleared _timeout with "if".
_message : string; _timeout: number;
get message() {
return this._message;
}
@Input()
set message(value: string) {
if (value && this._timeout == -1) {
this._timeout = setTimeout(function () {
clearTimeout(this._timeout);
this.message = null;
}.bind(this), 5000);
this._message = value;
}
}
Upvotes: 0