如果未选中任何复选框且输入为空,则禁用提交按钮

时间:2020-01-28 07:28:06

标签: angular

如果未选中任何复选框且输入为空,我想禁用“提交”按钮。 我已经尝试了以下代码。

https://stackblitz.com/edit/angular-ym1rda?file=src%2Fapp%2Fapp.component.html

3 个答案:

答案 0 :(得分:1)

我更改了您的 Stackblits demo 并将其修复。
您可以使用数组的some方法并检查对象之一是否具有checked值的'N'属性,然后禁用按钮。

app.component.ts

export class AppComponent implements OnInit {
  name = 'Angular';
  names:[] = [];
  isDisabled= false;
  ngOnInit(){
    this.names = [
      { id:'1', name: 'james', Initial: 'Mr', remark: '',checked: 'Y' },
      { id:'2', name: 'sam', Initial: 'Mr', remark: '',checked: 'Y'},
      { id:'3', name: 'john', Initial: 'Mr', remark: '', checked: 'N' }
    ];

    // added
    this.buttonState();
  }
  myFormSubmit(names){
    console.log(names);
  }

  // added
  buttonState() {
    return this.names.some(val => val.checked=='N');
  }
}

app.component.html

<button [disabled]="buttonState()" type="button" (click)="myFormSubmit(names)" >Submit</button>

答案 1 :(得分:0)

您可以创建一个检查条件的功能

areEnabled(value:any[])
  {
     let enabled=true;
     value.forEach(x=>{
       console.log(x)
       enabled=enabled && (x.checked=='Y' || x.remark)
     })
     return enabled
  }

然后您就可以使用

<button type="button" [disabled]="!areEnabled(names)" 
   (click)="myFormSubmit(names)" >Submit</button>

顺便说一句,您不尝试使用ReactiveForms吗?对我来说,这是使用表单并允许对输入进行更多控制,创建自定义验证器等的更“自然”的方式。

答案 2 :(得分:0)

使用函数检查状态并将其绑定到按钮的禁用属性。

component.ts

checkFormStatus(){
    let disable = false;
    // Iterate over names 
    this.names.forEach(
      n => {
        // If not checked and remark is empty 
        if(n.checked=='N' && n.remark==''){
          disable = true;
        }
      }
    );
    return disable;
}

component.html

<button [disabled]="checkFormStatus()">Submit</button>

演示:https://stackblitz.com/edit/angular-uq7pzo

相关问题