Cannot read property 'nativeElement' of un

2019-02-09 02:52发布

I am using ionic 2.

I need get htmlelement value.

Acutally i used viewchild.

Here is my html template code

<div class="messagesholder" *ngFor="let chat of chatval | orderby:'[date]'; let last = last">
       {{last ? callFunction() : ''}} 

   <div *ngIf="chat.sender == currentuser || chat.receiver == currentuser">    
     <p class="chat-date"  id="abc" #abc>{{chat.date | amDateFormat:'LL'}}</p>                 
              {{checkdate()}}                         
   </div>

chat.date value is firebase value. I access this element.But i didn't get the value of element.

Here is my component

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

    export class ChatPage   {
      @ViewChild(Content) content: Content;
      @ViewChild('abc')abc: ElementRef;
       constructor(){}

      ngAfterViewInit(){

       console.log("afterinit");
       console.log(this.abc.nativeElement.value);

      }
    }

I refered this link How can I select an element in a component template?

I tried to many way.

But i am getting this err

Cannot read property 'nativeElement' of undefined.

4条回答
The star\"
2楼-- · 2019-02-09 03:28

I think you should move your code from ngAfterViewInit to ngOnInit in order to avoid such kind of issues and not rely on timeout:

ngOnInit(){
  console.log("afterinit");
  console.log(this.abc.nativeElement.value);   
}
查看更多
爷的心禁止访问
3楼-- · 2019-02-09 03:29

Do not specify the type of variable abc. It should be like below:

 @ViewChild('abc') abc;
查看更多
成全新的幸福
4楼-- · 2019-02-09 03:35

declare Child component's selector into the Parent component html template. Otherwise, component object abc will not be initialized at runtime to call its functions or public properties at the parent.ts file.

Child Component abc:

@Component({
    selector: 'child-abc',
    templateUrl: './abc.component.html',
    styleUrls: ['./abc.component.css'],
})

At parent Component's html template declare child's selector:

< child-abc > < /child-abc >
查看更多
三岁会撩人
5楼-- · 2019-02-09 03:49

I think you are tring to get the value from html before rendering completely. If you try to print the value in a button click, it will works.

depend on your code I have modified a little.Try the below, it is working for me.

  ngAfterViewInit() {
    console.log("afterinit");
    setTimeout(() => {
      console.log(this.abc.nativeElement.innerText);
    }, 1000);
  }

Note: If not working, please increase the timeout time and try again.

查看更多
登录 后发表回答