[英]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
最终 - 工作更新:
将 #demo 添加到<p>
标签中,解决了这个问题。
谢谢你们...!
将 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.