如何获取 <p> 标签动态值并使用 angular 将其传递到打字稿中 2

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

我在 app.component.html

中有以下 html 标签
  <p id="demo">dynamicValuegoeshere!!!</p>

上面的段落有一些由 javascript 插入的动态值。但目前我正在使用类型脚本并尝试获取上述值并将其作为函数的输入参数传递。

我期待 app.component.ts 文件中的结果如下:

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

有人可以帮我实现这个吗?我如何读取特定的 <P> 标签值并将其传递到 app.component.ts 文件

更新:

我只是使用下面的代码在 app.component.ts 文件中获取结果

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

app.component.html:

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

输出:

null

但#demo 仍然有价值。

最新更新:

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);

输出:

this.dynamicRef.nativeElement.innerHTML

更新 - 最新:

二手alert(this.getValue())

返回:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

最终版 - 工作更新:

<p> 标签中添加 #demo 解决了这个问题。

谢谢大家...!

将 ViewChild 装饰器与模板引用和 ElementRef 包装器一起使用。

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
  }
}

如果您想确保在您的组件需要时 ViewChild 中的引用存在,请使用 ngAfterViewInit 挂钩而不是 ngOnInit。

这是一个工作示例(打开控制台):stackblitz