如何使用Angular从HTML检索特定值
目标:如何使用Angular从HTML检索特定值,html,angular,visual-studio-code,Html,Angular,Visual Studio Code,目标: 从语法代码“Tr”中的id中检索值,也从文本框名称“databox”中的值中检索值 当您按下“retrieve”(检索)按钮时,将执行检索这两个值的过程 问题: 当您按下“检索数据”按钮时,如何从html页面检索这两个值 我应该采取什么方法 我也不知道如何检索语法代码“tr”中的id Stackblitz: 谢谢大家! 您可以将item对象和input ref传递给submit函数,如下所示: <tr id="{{ item.id }}" *ngFor="let item
从语法代码“Tr”中的id中检索值,也从文本框名称“databox”中的值中检索值 当您按下“retrieve”(检索)按钮时,将执行检索这两个值的过程 问题:
当您按下“检索数据”按钮时,如何从html页面检索这两个值 我应该采取什么方法 我也不知道如何检索语法代码“tr”中的id Stackblitz:
谢谢大家! 您可以将item对象和input ref传递给submit函数,如下所示:
<tr id="{{ item.id }}" *ngFor="let item of datadata">
<td>{{ item.login }}</td>
<td>{{ item.node_id }}</td>
<td>{{ item.url }}</td>
<td>
<input id="box_ + {{ item.id }}" type="text" name="databox" #databoxInput><br>
<button (click)="submit(item, databoxInput)">Retrieve data</button>
</td>
</tr>
submit(clickedItem, inputref) {
console.log('clickedItem:', clickedItem, ' inputValue:', inputref.value)
}
因此,您将在submit函数中获得clicked item对象(包含单击行的全部数据)及其相应的输入值 使用ngModel作为解决方案 在组件中添加一个全局变量作为对象,并在输入中添加使用该变量作为ngModel,使用“id”作为该变量的键。还可以通过按钮单击传递id,因此每当按钮单击时,我们都可以根据id轻松获得输入框值 HTML:-
<tr id="{{ item.id }}" *ngFor="let item of datadata">
<td>{{ item.login }}</td>
<td>{{ item.node_id }}</td>
<td>{{ item.url }}</td>
<td>
<input id="box_ + {{ item.id }}" type="text" name="databox" [(ngModel)]="testModel[item.id]"><br>
<button (click)="submit(item.id)">Retrieve data</button>
</td>
</tr>
通过修改
submit
函数以包含一个参数(submit(item)
),您可以立即获取它们
关于功能:
submit(item) {
const input = <HTMLInputElement>(
document.getElementById(`box_ + ${item.id}`)
); // circumvent The property 'value' does not exist on value of type 'HTMLElement' see https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement for more detail
console.log(item.id, input.value);
}
提交(项目){
常量输入=(
document.getElementById(`box+${item.id}`)
);//规避“HtmleElement”类型的值上不存在属性“value”,请参见https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement 更多细节
console.log(item.id,input.value);
}
注意:您可以在控制台.log
上查看id和输入数据。可以自由地重用该值
submit(item) {
const input = <HTMLInputElement>(
document.getElementById(`box_ + ${item.id}`)
); // circumvent The property 'value' does not exist on value of type 'HTMLElement' see https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement for more detail
console.log(item.id, input.value);
}