22

I have tried to set the value of #name1 as shown below.But it shows compile time error as shown below.Can you please tell me how to set the value for the text component? Here I'm using one-way data bind and template-driven approach.

[ts] Property 'value' does not exist on type 'ElementRef'.

.html

<ion-input type="text" name="{{question?.name}}" #name1="ngModel" ngModel> </ion-input>

.ts

  @ViewChild('name1') name1: ElementRef;

  constructor(){

   }

 getAnswer(){
     this.name1.value = 'Hello';//here it shows the above error
  }
Sampath
  • 63,341
  • 64
  • 307
  • 441
  • Here's the documentation of ElementRef: https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html. But you're missing the whole point of ngModel, which is to be able to do bidirectional binding between the view and the state of the component. – JB Nizet May 08 '17 at 09:36
  • @Mr.Sampath... I am facing the similar error..please can you check out this link....https://stackoverflow.com/questions/49044826/property-value-does-not-exist-on-type-element – Heena Mar 01 '18 at 07:54

1 Answers1

35

Use the components type instead of a template variable

@ViewChild(TextInput) name1: TextInput;

This might also work (I don't know Ionic). It would work with a native HTML input element, but above is the preferred way if it's an Angular component.

this.name1.nativeElement.value = 'Hello';
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    This is not working `this.name1.nativeElement.value = 'Hello';`.But 1st one is working.Can you please share a good article about this concept? Thank you so much :) – Sampath May 08 '17 at 09:49
  • 2
    I didn't really expect the 2nd example to work. It would work with a native HTML input element. http://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681 might help – Günter Zöchbauer May 08 '17 at 10:17
  • @Sampath you'd have to edit to `this.name1.value = 'Hello';` – Chuks Jr. Nov 02 '21 at 01:20