【发布时间】: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!!!!
}
有人可以帮助我实现这一目标吗?如何读取特定的 <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,解决了这个问题。
谢谢大家...!
【问题讨论】:
-
你尝试过什么了吗?另外,你怎么称呼
getValue? -
我不知道如何获得价值。谷歌搜索,但到目前为止没有运气。
-
首先,你可以使用纯javascript
document.querySelector('#demo').innerHTML -
我不确定如何获取该
标记值。我的假设刚刚提到。甚至不确定它的预期效果。
-
你有一个Id,你可以使用函数
document.getElementById('demo')或document.querySelector('#demo')获取<p>标签的节点,你可以访问innerHTML属性来访问内容。请参阅我之前的评论。
标签: angular typescript angular2-services