Reputation: 89
I've constructed a modal which appears when there is an error. I'm displaying the message body based on an array which contains all my error message.
HTML:
<div class="popup_modal">
<div class="content" style="width: 28em;">
<div class="header" style="height: 5em;>
<p >Error Details.</p>
</div>
<div id="msgBody" class="body" style="height: 40vh;>
{{fetchMessage()}}
</div>
</div>
</div>
TS File:
fetchMessage()
{
var msg :string[] = [];
msg = this.getErrorMessage(this.messages); //this returns list of errors
for(var i=0;i<msg.length;i++)
{
var element:any = document.createElement("p");
element.innerHTML = msg[i]+'\n';
document.getElementById("msgBody").appendChild(element)
}
}
The problem is the error messages are repeated 4 times(even when the array returns only 1 item) and it multiplies every time I close and view the pop up modal. Not sure what I'm doing wrong.
Upvotes: 0
Views: 572
Reputation: 10969
Try changing code to :-
1. If you really want to call method in template :-
TS :-
fetchMessage()
{
var msg :string[] = [];
var msgBody = document.getElementById("msgBody");
msg = this.getErrorMessage(this.messages); //this returns list of errors
msgBody.innerHTML="";
for(var i=0;i<msg.length;i++)
{
var element:any = document.createElement("p");
element.innerHTML = msg[i]+'\n';
msgBody.appendChild(element)
}
}
2. Better Way
HTML :-
<div class="popup_modal">
<div class="content" style="width: 28em;">
<div class="header" style="height: 5em;>
<p >Error Details.</p>
</div>
<div id="msgBody" class="body" style="height: 40vh;>
<p *ngFor="let message of msg">{{message}}</p>
</div>
</div>
</div>
TS :-
public msg: string[] = [];
ngOnInit() {
this.fetchMessage();
}
fetchMessage(){
this.msg = this.getErrorMessage(this.messages);
}
Upvotes: 1
Reputation: 153
As it is in the loop every time it iterates.....Best solution is to remove from the loop
Upvotes: 0