Kevin Frostad Kevin Frostad - 2 months ago 16
HTML Question

Ionic 2/angular 2 - How do I add HTML elements with Typescript to my component?

Please don't dislike judging by the title, read the post first.

I've just started out learning typescript and angular 2 working with the ionic 2 framework.

I'm adding the html element referencing the typscript variable "newItem", like this:

<ion-content>
<ion-list inset>
<ion-item *ngFor="let item of todos" (click)="edit(item)">
{{item}}
</ion-item>
<ion-item>test</ion-item>
<div [innerHTML]=newItem></div>
</ion-list>
</ion-content>


In my typescript class for the component I have a function addTodo(), which sets the HTML for "newItem" when the pluss/add icon in the right corner is pressed:

addTodo(){
this.newItem = "<ion-item>test</ion-item>";
}


For some reason the "ion-item" tag is ignored on compilation and it only inserts "test" to the div element.

The appliction will look like this:

enter image description here

Component class:

enter image description here

So I tried to add this to the view:

<form *ngIf="editedItem">
<ion-item><input [(ngModel)]="newItem" name="newItem">
<ion-buttons end>
<button ion-button color="danger" (click)="btnCancel()">Cancel</button>
<button ion-button color="secondary" (click)="btnAdd()">Add</button>
</ion-buttons>
</ion-item>
</form>


But now when I click cancel or add, the page needs to reload.
I know I'm doing something wrong with the [(ngModel)]="newItem", should I try to pass the Angular variable over to the model or is there a better way to do this.

edit: Passed the variable over to the (click) function, as seen in @JoeriShoeby 's answer below.

In the model:

export class TodosPage {

newItem = "";
todos: string[] = this.getTodos();
editedItem: boolean = false;

constructor(public navCtrl: NavController) {

}

addTodo(){
this.editedItem = true;
}

btnAdd(){
this.todos.push(this.newItem);
this.editedItem = false;
}

btnCancel(){
this.editedItem = false;
}

getTodos(): string[]{

return ["item 1", "item 2"];
}
}

Answer

Your HTML file

// Your plus-icon in your header bar
<button (click)='toggleNew == true'>
    <ion-icon name='plus'></ion-icon>
</button>

// Your content
<ion-content>

  <ion-list inset>
    <ion-item *ngFor="let item of todos" (click)="edit(item)">
      {{item}}
    </ion-item>
  </ion-list>

    <ion-item *ngIf='toggleNew'>
        <ion-input [(ngModel)]='newItem' placeholder="Task .. "></ion-input>
        <button (click)='saveNew(newItem)'>Save</button>
        <button danger (click)='cancelNew()'>Cancel</button>
    </ion-item>
</ion-content>

Your component

// Initalial values.
newItem: string = "";
toggleNew: boolean = false;

// Saving function
saveNew( newItem: string ): void {
    this.todos.push(newItem);
    this.toggleNew = false;
    this.newItem = "";
}

// Cancel function
cancelNew(): void {
    this.toggleNew = false;
    this.newItem = "";
}