Search code examples
angulartypescriptangular5dynamic-html

Error while adding dynamic text in html Angular5


I am getting an issue while adding some text dynamically, its goes replaced. Here is my code

in html file

<textarea #messageInput></textarea>
<a href="javascript:void(0)" (click)="sendMessage(messageInput.value)"></a>

in ts file

export class className{

 flag :boolean=false;

   newMessage: any;

  sendMessage(msg:any) {

   this.flag=true

   this.newMessage=msg

 }

get flagVar(){
  return this.flag
}

}

in the same component html file I am trying to display as like

<div *ngIf='flagVar'>
<label  [hidden]="!forwardOption">
      <input type="checkbox" name="test" >  
 </label>
  {{msg}}
</div>

Instead of adding its replaced every time.

any help?

Thanks


Solution

  • Here you need a *ngFor for repeat your messages. The code you need to change:

    Here is an online DEMO

    HTML FILE:

    <textarea #messageInput></textarea>
    <a href="javascript:void(0)" (click)="sendMessage(messageInput.value); messageInput.value = ''">Add Message</a>
    
    <div *ngIf="mesasgeList.length > 0">
      <div *ngFor="let msg of mesasgeList">
        <label [hidden]="!forwardOption">
          <input type="checkbox" name="test" >  
     </label> {{msg}}
    </div>
    </div>
    

    TS FILE:

    export class AppClass {
    flag: boolean = false;
      forwardOption: boolean;
      mesasgeList = [];
      sendMessage(msg: any) {
    
        this.flag = true;
        this.forwardOption = true;
        this.mesasgeList.push(msg);
    
      }
    
      get flagVar() {
        return this.flag
      }
    }
    

    Hope it's help you.