簡體   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