Ionic2 add element in view

3

I need to create a click event that when pressed creates an input in the view. How can I do this ? Thank you Ps: use ionic2 typescript

HTML

<ion-navbar *navbar>
  <ion-title>
    POSimplex
  </ion-title>
</ion-navbar>

<ion-content class="home" padding>
  <button ion-button full>Login</button>
  <p>
    <button ion-button full>Criar conta</button>
  </p>
  <p>{{ sl }}</p>
</ion-content>

Typescript

import {Component} from "@angular/core";
import {NavController} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  sl: string
  constructor(private navController: NavController) {this.sl = '<button ion-button full>Criar conta</button>'}
}
    
asked by anonymous 06.10.2016 / 01:16

1 answer

3

Place the click event:

<button ion-button full (click)="inserirCampo()">Adicionar campo</button>

As you may know, Ionic uses AngularJS, the "infinite" insertion of elements in the DOM (which I usually do), is to have a div containing a repeater ( ngFor ) working on a scope variable .

<div *ngFor="let item of inputs">
    <input type="text">
</div>

With this, in your function inserirCampo you will insert a new item in your scope variable:

this.inputs.push(novoItem);

Having the two way data binding of the Angular, once you enter in the scope variable, the input will be displayed on the page.

Typescript:

export class MinhaPagina {
  inputs: Array<{title: string, type: string, value: string}>;

  constructor(public navCtrl: NavController, public navParams: NavParams) {

      this.inputs = [
          { title: "teste", type: "text", value: "valor" },
          { title: "teste2", type: "text", value: "valor2" }
      ];
  }

  adicionarCampo() {
      this.inputs.push({ title: "teste", type: "text", value: "valor" });
  }
}

.html

<ion-content>
    <ion-list>
        <ion-item *ngFor="let item of inputs">
            <ion-label fixed>{{item.title}}</ion-label>
            <ion-input type="{{item.type}}" value="{{item.value}}"></ion-input>
        </ion-item>
    </ion-list>
    <button ion-button class="button" (click)="adicionarCampo()">Adicionar campo</button>
</ion-content>

  

Obs. Your code did not work because you used * ngfor instead of * ngFor

    
06.10.2016 / 01:42