0

I would like to get value and not the viewValue from a Reactive Form control. I am only able to get the viewValue. I will explain what I mean by this below.

I have looked into SO articles like How to get values of reactive form inputs in Angular? but that talks about the value that is in the view, not the value itself. I have tried adding .viewValue to the end but when building I get an error "Property 'viewValue' does not exist on type 'AbstractControl"

HTML:

<mat-form-field>                            
   <mat-select placeholder="Language" formControlName="language2" required>
       <mat-option *ngFor="let language of languages2" [value]="language.value">
            {{ language.viewValue }}
        </mat-option>
    </mat-select>
</mat-form-field>

TS:

this._profileForm = this.fb.group({
'language2': [this.languages2]
});

this.languages2 = [
            { value: 1, viewValue: this.englishReg },
            { value: 2, viewValue: this.spanishReg }
        ];

if (this._profileForm.controls["language2"].value == null)
        this._profileForm.controls["language2"].setValue(this.languages2.filter(item => item.value === 1)[0].viewValue);


console.log(this._profileForm.get('language2').value);

Actual result: prints "Ingles" Expected Result: However, I want to get the value 1, when the user selects Ingles

4
  • I misunderstood question, therefore deleted answer :D Setting the value like that should work. But also remove required from template, set it on the form control. Also don't assign the array as the value of the formcontrol. It will be overwritten, but anyway. Commented Feb 8, 2019 at 18:59
  • Please create a demo showing the issue, since those above issues shouldn't affect this at all. Commented Feb 8, 2019 at 18:59
  • languages2 is an array, so you are missing and index, to access the value. i.e. if (this._profileForm.controls["language2"].value or... this._profileForm.get('language2').value. By . contrast the HTML part makes sense. Commented Feb 8, 2019 at 20:28
  • stackoverflow.com/a/47011785/495157 Commented Feb 8, 2019 at 20:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.