带有空格的输入字段仅不允许保存成角度?

时间:2018-10-19 06:12:38

标签: html angular

在这里,当我单击SAVE按钮时,我有一个输入字段,它进入了saveNewCategory()函数并检查它是否为空,但是当我在输入字段中仅放空格时,这也是保存,那么当在输入字段中仅给出空格时,如何不允许保存输入字段?

category.component.html

<div>
  <form method="post" enctype="multipart/form-data">
    <mat-form-field>
     <input matInput placeholder="Category Title" maxlength="30" name="categorytitle" [(ngModel)]="this.categoryObj.categorytitle" required>
    </mat-form-field>
  </form>
  <button mat-raised-button color= "accent" (click)="saveNewCategory()">SAVE</button>
</div>

category.component.ts

saveNewCategory(){
  if(this.categoryObj.categorytitle != ''){
    const formData = new FormData();
    formData.append('categorytitle',this.categoryObj.categorytitle);
    this.categoryService.saveNewCategory(formData).subscribe(
      (data) => {
        if(data != undefined && data.status == 1){
          this.snackBar.open('New Category Saved Successfully..!!', '',{
            duration: 2000
          });  
        }
      }
    )
  }else{
    this.snackBar.open('Category Image is required..!!', '',{
      duration: 2000
    });  
  }  
} 

1 个答案:

答案 0 :(得分:1)

您可以将trim方法用作:

saveNewCategory(){
  if(this.categoryObj.categorytitle.trim() != ''){ <===== Here
    const formData = new FormData();
    formData.append('categorytitle',this.categoryObj.categorytitle);
    this.categoryService.saveNewCategory(formData).subscribe(
      ...
    )
  }else{
    ...
  }  
}