离子警报强制输入

时间:2017-12-10 05:46:00

标签: angular typescript ionic-framework ionic3

我正在使用离子3作为我的新应用程序,我需要从我的离子警报控制器获取输入是强制性的。通过离子组件文档和api文档,但无法找到如何执行此操作。以下是我的代码。我想将名称移动输入设为必填项,并禁用继续按钮,直到两者都填满为止。

let prompt = this.alertCtrl.create({
        title: 'Tell us about yourself',
        message: "Please provide us your name, and mobile number",
        inputs: [
        {
          name: 'name',
          placeholder: 'Name'
        },
        {
          name: 'mobile',
          placeholder: 'Mobile number'
        },],
        buttons: [
        {
          text: 'Cancel',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Continue',
          handler: data => {
            console.log('Continue clicked');
          }
        }]
        });
        prompt.present();

2 个答案:

答案 0 :(得分:1)

此时你无法做到这个。但是使用数据验证规则可以防止用户输入无效数据。

我在这里使用了toast次无效数据通知。

{
  text: 'Done',
  handler: (data) => {
    if (EmailValidator.isValid(data.email)) {
      if (this.data) {
        //
      } else {
       //
      }
      return true;
    } else {
      this.showErrorToast('Invalid Email');
      return false;
    }
  }
}

答案 1 :(得分:0)

对于仍在寻找解决方法的任何人,这是我所做的,不仅在Ionic 3中,而且在Ionic 4中。

您可以强制输入,确认后验证数据,甚至通过document对象使用某些 DOM操作来更新警报消息。

基本上,您想打开警报并查询所有您感兴趣的输入或按​​钮。然后,您可以在输入中添加一些侦听器以启用或禁用任何其他元素。

示例(离子4)

    const alert = await this.alertCntrl.create({
      header: 'Alert!',
      subHeader: 'Delete item',
      message: 'Please fill the following code to confirm deletion: XYZ',
      inputs: [{type: 'text', placeholder: 'Confirmation code', id: 'code'}],
      buttons: [
        {text: 'Confirm', handler: _data => this.deleteItem(), cssClass: 'confirm'},
        {text: 'Cancel', role: 'cancel'},
      ],
    });
    await alert.present();

    const code$ = new Subject();

    const confirmBtn = document.querySelector('.confirm') as HTMLButtonElement;
    confirmBtn.disabled = true;

    const codeInput = document.getElementById('code') as HTMLInputElement;

    codeInput.addEventListener('keyup', () => codigo$.next(codeInput.value));

    code$.asObservable().subscribe(code => confirmBtn.disabled = code !== 'XYZ');

要显示该按钮已禁用,我向离子 global.scss

中添加了一些CSS
// This will match the class that we set up to the btn in the alert config.
// and color the btn text to grey only when it is disabled
button.confirm:disabled {
  color: grey;
}