微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/angularjs/141098.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐