Ii 如何在我的组件中获取 ionic 2 中的输入值?

How Ii can get input value within ionic 2 in my Component?

我将使用 ionic 2 创建一个购物应用程序。在产品详细信息中,我创建了一个用于增加和减少数量值的步进器。

如何在我的组件中获取 ionic 2 内的输入值?

解法:

1- app/pages/index.html

在Angular2中,你应该在模板中使用ngModel

<ion-header>
  <ion-navbar primary>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-item>
    <button lightgray full (click)="incrementQty()">+</button>
    <ion-item>
      <ion-input type="number" min="1" [value]="qty" [(ngModel)]="qty"></ion-input>
    </ion-item>
    <button lightgray full (click)="decrementQty()">-</button>
  </ion-item>
</ion-content>

2- app/pages/index.ts

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

@Component({
  templateUrl: 'build/pages/titlepage/titlepage.html',
})
export class titlePage {
  qty:any;
  constructor(private nav: NavController) {
    this.qty = 1;
  }

  // increment product qty
  incrementQty() {
    console.log(this.qty+1);
    this.qty += 1;
  }

  // decrement product qty
  decrementQty() {
    if(this.qty-1 < 1 ){
      this.qty = 1
      console.log('1->'+this.qty);
    }else{
      this.qty -= 1;
      console.log('2->'+this.qty);
    }
  }
}

或者作为替代解决方案,您可以使用为 angular 设计的更合适的 Form 控件 2. (learn more here )

示例:

打字稿

import {Component, Input} from '@angular/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, AbstractControl} from '@angular/common';
import {IONIC_DIRECTIVES} from 'ionic-angular';

@Component({
    selector: 'chat-form',
    templateUrl: '/client/components/chat-form/chat-form.html',
    directives: [IONIC_DIRECTIVES, FORM_DIRECTIVES],
    pipes: [],
    styleUrls: []
})
export class ChatFormComponent {
    
    chatForm:ControlGroup;
    
    messageInput:AbstractControl;

    constructor(private translate:TranslateService, private formBuilder:FormBuilder) {
        this.chatForm = formBuilder.group({messageInput: ['']})
        this.messageInput = this.chatForm.controls['messageInput'];
    }

    sendMessage() {
        console.log('sendMessage: ', this.messageInput.value);
    }
}

模板

<form [ngFormModel]="chatForm" (ngSubmit)="sendMessage()">
    <ion-input type="text" [ngFormControl]="messageInput" placeholder="{{'chat.form.placeholder' | translate }}"></ion-input>
    <button fab>
        <ion-icon name="send"></ion-icon>
    </button>
</form>