【问题标题】:How to fetch the <p> tag dynamic value and pass it into typescript using angular 2如何获取 <p> 标签动态值并使用 Angular 2 将其传递给打字稿
【发布时间】:2020-01-28 19:18:07
【问题描述】:

我在 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!!!!
}

有人可以帮助我实现这一目标吗?如何读取特定的 &lt;P&gt; 标签值并将其传递到 app.component.ts 文件中

更新:

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

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

app.component.html

&lt;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

最终 - 工作更新

&lt;p&gt; 标签中添加了#demo,解决了这个问题。

谢谢大家...!

【问题讨论】:

  • 你尝试过什么了吗?另外,你怎么称呼getValue
  • 我不知道如何获得价值。谷歌搜索,但到目前为止没有运气。
  • 首先,你可以使用纯javascript document.querySelector('#demo').innerHTML
  • 我不确定如何获取该

    标记值。我的假设刚刚提到。甚至不确定它的预期效果。

  • 你有一个Id,你可以使用函数document.getElementById('demo')document.querySelector('#demo')获取&lt;p&gt;标签的节点,你可以访问innerHTML属性来访问内容。请参阅我之前的评论。

标签: angular typescript angular2-services


【解决方案1】:

将 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

【讨论】:

  • 我需要在文件中提及模板吗?因为

    的值是动态的,在 app.component.html 文件中。

  • 不,模板可以是内联也可以是网址,没关系。
  • 如果要在ngOnInit中使用,需要使用static:true @ViewChild('dynamic', { static: true }) private dynamicRef
  • 仍然失败。用最新发现更新了问题
  • 您需要使用角度模板引用,而不是 HTML id。这个:&lt;p #demo&gt;value&lt;/p&gt;,不是:&lt;p id="demo"&gt;value&lt;/p&gt;
猜你喜欢
  • 1970-01-01
  • 2018-01-12
  • 2015-03-01
  • 2021-06-19
  • 2016-09-08
  • 1970-01-01
  • 2017-05-16
  • 2018-10-20
  • 2023-03-22
相关资源
最近更新 更多