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

Please do not laugh at judging by the name, first read the message.

I just started to study typescript and angular 2, working with base with ionic 2.

I add an html element that references the typscript variable "newItem", for example:

<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 the addTodo () function that sets the HTML for "newItem" when you click the pluss / add icon in the right corner:

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

For some reason, the "ion-item" tag is ignored during compilation, and it only inserts a "test" into the div element.

The application 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 should reload. I know that I am doing something wrong with [(ngModel)] = "newItem", should I try to pass the angular variable to the model or is there a better way to do this.

edit: passed the variable to the function (click), as shown 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"]; } } 
+5
source share
1 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 = ""; } 
+4
source

Source: https://habr.com/ru/post/1257657/


All Articles