简体   繁体   中英

How to fetch the <p> tag dynamic value and pass it into typescript using angular 2

I have the below html tag in app.component.html

  <p id="demo">dynamicValuegoeshere!!!</p>

The above paragraph is having some dynamic value which is inserted by javascript. But currently i'm using type script and trying to get the above value and pass it as input argument of function.

I'm expecting the outcome like below in app.component.ts file:

getValue(dynamicvalue){
console.log(dynamicvalue)  //It should print the current value of the <p id="demo"> which is dynamicvaluegoeshere!!!!
}

can someone help me to achieve this? How can I read the particular <P> tag value and pass it into app.component.ts file

Updated:

I just used the below code to fetch the result in app.component.ts file

getValue()
{
 alert(document.getElementById("#demo").innerHTML);
}

app.component.html :

<input type="submit" value="Submit" (click)="getValue()" id="submitBtn2" class="btn-primary btn-xs" >

Output:

null

But the #demo still had value.

Updates-latest:

app.component.ts :

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

     export class AppComponent implements OnInit {
      @ViewChild('demo', { static: false }) private dynamicRef: ElementRef<HTMLElement>;

     getvalue() {
       return this.dynamicRef.nativeElement.innerHTML;    
    }

     alert(this.getvalue);

Output:

this.dynamicRef.nativeElement.innerHTML

在此处输入图片说明

Updates - latest:

Used alert(this.getValue())

returned :

ERROR TypeError: Cannot read property 'nativeElement' of undefined

Final - Working Update :

Added #demo into the <p> tag which resolved this issue.

Thank you all...!

Use the ViewChild decorator along with a template reference and an ElementRef wrapper.

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

@Component({
  selector: 'my-app',
  template: '<p #dynamic>Dynamic value</p>',
})
export class AppComponent implements AfterViewInit {
  @ViewChild('dynamic', { static: false }) private dynamicRef: ElementRef<HTMLElement>;

  get value() {
    return this.dynamicRef.nativeElement.innerHTML;    
  }

  ngAfterViewInit() {
    console.log('value of p: ', this.value) // value of p: Dynamic value
  }
}

If you want to make sure the reference in the ViewChild is present when your component needs it, use the ngAfterViewInit hook instead of ngOnInit.

Here's a working example (open console): stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM