Home > OS >  how to show the mat select option input, based on a another input value's character
how to show the mat select option input, based on a another input value's character

Time:08-19

Basically I am a beginner to Angular as well as typescript. Here am trying to validate a Reactive form Text field with some conditions.

my condition is

  1. there is 2 fields - a)input fields b) select field
  2. In input field it is based on a 15 digit field. in that 13,14,15th character will be alphabets
  3. In second field, there is two select options. i) public sector ii) private sector
  4. if the 13,14,15th alpahabet is 'GOI' means, in select field automatically it should be selected as 'public sector' or else user can select their options in select field.

someone help me out !

Thanks in advance

CodePudding user response:

I would seperate the logic from the HTML.

In the HTML you would have your input and the select:

<input type="text" [(ngModel)]="inputValue" (ngModelChange)="checkGOI()" />

<select>
    <option value="PS">Public Sector</option>
    <option value="PVS">Private Sector</option>
</select>

In the .ts file you now need a variable "inputValue" and function which checks, if the digits 13,14 an 15 are equal to GOI and sets the result to a boolean:

  public inputValue: string = '';
  public containsGOI: boolean = false;

  public checkGOI(): void {
    this.containsGOI = this.inputValue.substring(12, 15) === 'GOI';
  }

Now you can modifiy the select and the option like this:

<select [disabled]="containsGOI">
  <option value="PS" [selected]="containsGOI">Public Sector</option>
  <option value="PVS">Private Sector</option>
</select>

If the inputValue contains GOI, the select is disabled and PS is selected.

Also keep in mind, that substr is deprecated (Why is String.prototype.substr() deprecated?)

CodePudding user response:

You can do something like below:

<input type="text" [(ngModel)]="model.inputField" 
(blur)="model.inputField.substr(12) == 'GOI' ? 
 model.selectField ='PS' : ''" name="inputField">

<select [(ngModel)]="model.selectField" 
   name="selectField">
  <option value="PS">Public Sector</option>
  <option value="PVS">Private Sector</option>
</select>

When user will enter data in input field then on blur event we can check the last three characters using substr method and if the condition is true then the select field will populate with public sector else user can select on it's own.

Hope this helps.

  • Related