0

I want to get the value of ion-textarea inside component in Ionic 2 but I have always this error

Cannot read property 'value' of undefined

Code HTML:

<ion-textarea   #preferences id="preferences" placeholder="Veuillez mentionner vos préferences"></ion-textarea>

component .ts:

@ViewChild('preferences') m_preferences;
let preferences : this.m_preferences.nativeElement.value;
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
RII
  • 13
  • 1
  • 7

2 Answers2

2

When you apply template reference variable on component element then by default you will get a component instance.

How to get reference of the component associated with ElementRef in Angular 2

In your case you applied preferences to ion-textarea component. It's TextInput component that has value property

https://github.com/ionic-team/ionic/blob/fed4fd95d2545c324c45d891b837e2bcc4ded79d/src/components/input/input.ts#L144

So you should simple do like this:

import { TextInput } from 'ionic-angular';
...
@ViewChild('preferences') m_preferences: TextInput;

addProduct() {
  console.log(this.m_preferences.value);
}

I also prepared Stackblitz Example

You can also do it without ViewChild:

<ion-textarea #preferences ...></ion-textarea>
<button (click)="addProduct(preferences.value)">Add product</button>

addProduct(value) {
  alert(value) 
}

Stackblitz Example

If you deal with angular forms then consider @GreyBeardedGeek answer

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • @user3033938 Consider accepting the answer if it helped – yurzui Nov 23 '17 at 16:03
  • While this will work, I believe that the more correct way to do this is to bind the ion-textarea's value to a component property, using ngModel, instead of using @ViewChild. See my comment below. – GreyBeardedGeek Nov 23 '17 at 16:52
1

From the documentation:

Note that must load its value from the value or [(ngModel)] attribute. Unlike the native element, does not support loading its value from the textarea's inner content.

So, what you are trying to do is not.supported. You should bind a property to the control instead.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • Here's @yurzui's stackblitz updated show the correct way to do it: https://stackblitz.com/edit/ionic-3fvd11?file=pages%2Fhome%2Fhome.html – GreyBeardedGeek Nov 23 '17 at 16:50
  • `must load its value from the value or [(ngModel)] attribute` In my solution i read it from **the value** not from nativeElement. I don't want to import FormsModule in my @NgModule – yurzui Nov 23 '17 at 17:48