繁体   English   中英

在角度 7 中使用 *ngIf 更改变量值

[英]change a variable value using *ngIf in angular 7

我正在尝试在 angular 7 应用程序中使用 [pattern] 添加一些验证。 如果模式有错误( phoneNumber.errors?.pattern ),我想使用变量this.isSubmitDisabled禁用按钮。

我知道这可以使用反应式表单来实现,但不幸的是,我不能使用表单。 如果phoneNumber.errors?.patterntrue有没有办法将变量值设置为“true”?

这是我的代码:

<input 
  type="text" 
  class="form-control" 
  (ngModelChange)="dialInDetailsChange($event)" 
  name="dialInDetails" 
  [disabled]="false" 
  id="dialInDetails" 
  pattern="^\d+(?:[,.]\d+)?$" 
  required 
  [(ngModel)]="agendaMeeting.dialInDetails" 
  ngModel #dialInDetails="ngModel" />

您还可以使用.ts文件中的.match()来检查它。 在模型更改时只需检查输入的值是否与您的regex匹配。 如果匹配,则将inputDisabled设置为false否则将inputDisabled设置为true

let inputDisabled:boolean = false;
dialInDetailsChange(event:any){
  if(agendaMeeting.dialInDetails.match("^\d+(?:[,.]\d+)?$") === null){
    inputDisabled = true;
  }
  else{
    inputDisabled = false;
  }
}

最近评论后编辑

工作演示链接

myInput='';
result='';
  changeHandler(){
    if(this.myInput.match('^[\\s]+[a-zA-Z]*')  === null){
      this.result = "correct input";
    }
    else{
      this.result = "there are spaces at the begining."
    }
  }

我认为您不能在模板中使用表达式分配值,请查看文档

You can't use JavaScript expressions that have or promote side effects, including:
  • 赋值 (=, +=, -=, ...)
  • new、typeof、instanceof等操作符。
  • 用 ; 链接表达式或者 ,
  • 递增和递减运算符 ++ 和 --
  • 一些 ES2015+ 运算符

尝试这个 :

<input 
  type="text" 
  class="form-control" 
  (ngModelChange)="updateState(phone)" 
  name="dialInDetails" 
  [disabled]="false" 
  id="dialInDetails" 
  pattern="^\d+(?:[,.]\d+)?$" 
  required 
  [(ngModel)]="agendaMeeting.dialInDetails" 
  #phone="ngModel" />    

<button type="button" [disabled]="isDisabled">Submit</button>


updateState(input){
    this.isDisabled = input.errors && input.errors.pattern ? true : false ;
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM