mano10
mano10

Reputation: 449

get select option attribute value reactive form

Hi I`m using Angular 6 reactive.

This is select control

<select _ngcontent-c2="" class="floating-select ng-untouched ng-pristine ng-invalid" formcontrolname="user" value="" ng-reflect-name="user">
   <option _ngcontent-c2="" value="adduser" ng-reflect-value="adduser">--Add User--</option>
   <!--bindings={
      "ng-reflect-ng-for-of": "[object Object],[object Object"
      }-->
   <option _ngcontent-c2="" value="1: gokulanathan.s" ng-reflect-ng-value="gokulanathan.s" usrstatus="ACTIVE">gokulanathan.s</option>
   <option _ngcontent-c2="" value="2: subin.abraham.ext" ng-reflect-ng-value="subin.abraham.ext" usrstatus="ACTIVE">subin.abraham.ext</option>
   <option _ngcontent-c2="" value="3: subin.abraham.ext" ng-reflect-ng-value="subin.abraham.ext" usrstatus="INACTIVE">subin.abraham.ext</option>
   <option _ngcontent-c2="" value="4: manoj.g.ext" ng-reflect-ng-value="manoj.g.ext" usrstatus="ACTIVE">manoj.g.ext</option>
   <option _ngcontent-c2="" value="5: rajesh.augustine" ng-reflect-ng-value="rajesh.augustine" usrstatus="ACTIVE">rajesh.augustine</option>
</select>

Is it possible to get "usrstatus" attribute value with formcontrol

This is my formBuilder code

  this.form = this.formBuilder.group({
      clientid: ['', Validators.required],
      user: ['', Validators.required],
      username: ['', Validators.required],
      status: ['', Validators.required]       
  });

I`m looking for something like this..."this.form.controls["user"].usrstatus". please help..

Upvotes: 0

Views: 1300

Answers (2)

Suryan
Suryan

Reputation: 659

I am not sure about the this.form.controls["user"].usrstatus and I don't think it's possible to get attribute value like this (correct me if I am wrong) but you can have the change event on select

<select _ngcontent-c2="" class="floating-select ng-untouched ng-pristine ng-invalid"
formcontrolname="user" value="" ng-reflect-name="user" (change)="getAttributeValue($event)">

and in you component

getAttributeValue(event) {
    const selectEl = event.target;
    const attrVal = selectEl.options[selectEl.selectedIndex].getAttribute('usrstatus');
    console.log(attrVal)
}

Upvotes: 2

Tomer Halaf
Tomer Halaf

Reputation: 43

I am not sure but i think it impossible to get second value from select option like this.

first please change formcontrolname to formControlName.

than in your option value set value='{"user": "1: gokulanathan.s", "status": "ACTIVE"}'

you can create new class or interface to receive those 2 values or you can use JSON.parse method and access your values like this:

JSON.parse(this.form.get("user").value).user;

JSON.parse(this.form.get("user").value).status;

you can read more about formControlName here: https://angular.io/api/forms/FormControlName

Upvotes: 0

Related Questions