首页 文章

Ionic 2 / angular 2 - 如何使用Typescript将HTML元素添加到我的组件中?

提问于
浏览
7

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

我刚刚开始学习使用离子2框架的typescript和angular 2 .

我正在添加引用typscript变量“newItem”的html元素,如下所示:

<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>

在我的组件的typescript类中,我有一个函数addTodo(),当按下右角的pluss / add图标时,它设置“newItem”的HTML:

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

由于某种原因,编译时会忽略“ion-item”标记,它只会向div元素插入“test” .

申请将如下所示:

enter image description here

组件类:

enter image description here

所以我尝试将其添加到视图中:

<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>

但现在当我单击取消或添加时,页面需要重新加载 . 我知道我对[(ngModel)] =“newItem”做错了,我应该尝试将Angular变量传递给模型,还是有更好的方法来做到这一点 .

编辑:将变量传递给(单击)函数,如@JoeriShoeby在下面的答案中所示 .

在模型中:

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"];
  }
}

1 回答

  • 4

    你的HTML文件

    // 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>
    

    你的组件

    // 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 = "";
    }
    

相关问题