简体   繁体   中英

change a variable value using *ngIf in angular 7

I am trying to add some validation using [pattern] in an angular 7 application. I want to disable a button using a variable this.isSubmitDisabled if the pattern has errors ( phoneNumber.errors?.pattern ).

I know that this can be achieved using Reactive form but unfortunately, I cannot use forms. Is there a way to set the variable value to 'true' if phoneNumber.errors?.pattern is true ?.

Here is my code:

<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" />

You can also check it using .match() in your .ts file. On model change just check whether the entered value matches your regex . If matches then set inputDisabled to false otherwise set inputDisabled to true .

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

Edit after recent comment

WORKING DEMO : LINK

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."
    }
  }

i think you can't assign values using expression in your template, check the documentations

You can't use JavaScript expressions that have or promote side effects, including:
  • Assignments (=, +=, -=, ...)
  • Operators such as new, typeof, instanceof, etc.
  • Chaining expressions with ;or ,
  • The increment and decrement operators ++ and --
  • Some of the ES2015+ operators

try this :

<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 ;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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