22

how to get html element value using ionic 2

Below my html code

 <div class="messagesholder" *ngFor="let chat of chatval | orderby:'[date]'" >
   <div *ngIf="chat.sender == currentuser || chat.receiver == currentuser">
    <div  *ngIf="chat.date" style="text-align: center;" >
           <p style="font-size:9px;" id="amount" #amount>{{chat.date | amDateFormat:'LL'}}</p>
           <input #myname [ngModel]="range" (ngModelChange)="saverange($event)"/>
         <input #myname type="text" value={{chat.date}}>
    </div>
   </div>
   <div class="message" *ngIf="chat.sender == currentuser || chat.receiver == currentuser" [ngClass]="{'me': currentuser == chat.sender}">
          <div class='image' *ngIf="chat.path" >
            <img *ngIf="chat.path" [src]="chat.path"/><br>
            <span *ngIf="chat.path_text">{{chat.path_text}}</span>
            <span style="font-size:9px;">{{chat.date | amDateFormat:'hh:mmA'}}</span>
          </div> 
           <div *ngIf="chat.message_text">
           <span>{{chat.message_text}}</span>
           <span style="font-size:9px;">{{chat.date | amDateFormat:'hh:mmA'}}</span>
           </div>
    </div>

Below my ts file

import { Component,Inject,ViewChild,ElementRef,AfterViewInit} from '@angular/core';

export class ChatPage implements AfterViewInit {
  @ViewChild('myname') input:ElementRef; 
  constructor(public modalCtrl: ModalController,public navCtrl: NavController) {}
   ngAfterViewInit() {
    console.log(this.input.nativeElement.value);
    }
  }

Same date values are repeated.I want same date values are not repeated.

Because I will check two variable.

so I need chat.date value.because i binded the value of input.But i cannot get the value of input element.

i am getting this error

Cannot read property 'nativeElement' of undefined

How to fix this issue.or any other way to find slutions.

Thanks

11
  • why do you want to use ElementRef, you can simply use ngModel Commented Mar 16, 2017 at 5:56
  • Thanks.How can I consoled the ngModel value in constructor. Commented Mar 16, 2017 at 6:00
  • are you assigning any value when u initialize the component for the first time Commented Mar 16, 2017 at 6:09
  • No.I does not assign any value in component. Commented Mar 16, 2017 at 6:12
  • Then you will get undefined Commented Mar 16, 2017 at 6:45

6 Answers 6

33

I created a plnkr link: https://plnkr.co/edit/49TEP8lB4lNJEKsy3IDq?p=preview

It works for me so probably you may want to create your own plnkr so ppl can help

export class ApiDemoApp{
  root = ApiDemoPage;
  @ViewChild('myname') input:ElementRef; 
  constructor() {
  }
  ngAfterViewInit() {
  console.log(this.input.nativeElement.value);
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

.Thanks for ur reply.Ya.I implement my component.But still getting same error
Man, I have no idea, can you post everything about your component, I created a plunker and it works! Check out my answer for the link
implements AfterViewInit is just a Typescript construct which gets removed on transpilation to javascript..It is used to make sure you have implemented the correct lifecycle hook.. that really doesnt make a difference in this case
any other way to get input element value. I tried another way console.log(< HTMLInputElement > document.getElementById('amount').value); Its consoled the value of null.
The way you are doing is the correct way so there must be something else in your code causing it.
|
9

Use this code

@ViewChild('myname') input:any; 

ngAfterViewInit() {
 console.log(this.input.nativeElement.value) ;      
}

7 Comments

Thanks for ur reply.I use this code. i am getting following error Cannot read property 'changes' of undefined
I think Mubashir meant to write this.input.changes..
I use also this.input.changes.Still get the same error
remove type 'hidden' with 'text' in input tag
Still i get this same error Cannot read property 'changes' of undefined.otherwise i used <p style="font-size:9px;" id="amount" #amount>User name</p> How can i access this value.any other way to get input element value.Kindly help me.
|
4

If you using Directive Try this way:

private el: HTMLInputElement;
constructor(private _elementRef: ElementRef) {
    this.el = this._elementRef.nativeElement;
}

ngOnInit(): void {
    console.log(this.el.value);
}

Comments

1

Your input element depends on the *ngIf condtion.

<div *ngIf="chat.sender == currentuser || chat.receiver == currentuser">
    <div *ngIf="chat.date" style="text-align: center;">
        <input #myname [ngModel]="range" (ngModelChange)="saverange($event)" />
        <input #myname type="text" value={{chat.date}} />
    </div>
</div>

ngIf directly manipulates the DOM. If the value is false your html element along with the outer div container gets removed from the DOM. Check here This is why your ViewChild is undefined. You will need to check for the same conditions in your component or reconsider the logic where you are accessing the element in your component. Try this:

ngAfterContentInit() {
    console.log(this.input.nativeElement.value);
    }

11 Comments

Thanks.But.I have chat.date values are same.Pls refer this imgur.com/dpnLSSv I need same date values are does not show.How to fix it.
Try angular.io/docs/ts/latest/api/core/index/… ngAfterContentInit lifecycle hook
Still.I am get this same error msg.But all if conditions are true.i have no idea.How to fix same date values are does not show.
No.does not wrk without ngIf.still get the same err.native element is undefined.
have you tried injecting elementRef in the constructor and this.elementRef.getElementById("id_of_input")?
|
0

If anyone interested how to check if nativeElement has empty data inside then use textContent property.

Suppose we have following HTML output from nativeElement.outerHTML:

<div _ngcontent-c8="" checkifelementempty="" class="some-class">
  <div _ngcontent-c8="">
     <b><i>&nbsp;a</i></b>
  </div>
</div>

To check if above HTML has empty text use this: !nativeElement.textContent.trim()

Comments

0

Use ngModel.

On the basis of your code I made a small change to use ngModal. see this.

import { Component,Inject,ViewChild,ElementRef,AfterViewInit} from '@angular/core';

export class ChatPage implements AfterViewInit {
  myname: string;
  constructor(public modalCtrl: ModalController,public navCtrl: NavController) {}
   ngAfterViewInit() {
    console.log(this.myname);
    }
  }
<input [(ngModel)]="myname" type="hidden" value="John Doe">

7 Comments

.I used this.consoled the value of this.myname is undefined .
You need to initialize the variable myname with your default value. In you case I think default value is 'John Doe'. So use this myname: string = 'John Doe';
k.But i dont need any initialize value and assing input tag. acutally i change my tag <p style="font-size:9px;" id="amount" #amount>{{chat.date | amDateFormat:'LL'}}</p> chat.date value binded to input tag.then how can i get this value
Use chat.date as ngModal
Your question is not clear. Please specify your question. Use example if needed.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.