Ionic 2/angular 2 – 如何将带有Typescript的HTML元素添加到我的组件中?

请不要不喜欢标题判断,先阅读帖子.

我刚开始学习使用离子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”.

申请将如下所示:

组件类:

所以我试着将它添加到视图中:

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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...