如何知道html元素在Angular Form中的位置



单击"添加字段"按钮时,我正试图在表单中获取位置,该按钮(单击(="getFormPosition"单击该按钮后,我想在表单中获得位置,因此在这种情况下,我想获得:(SaleToPOIRequest.DiagnosisRequest(或SaleToPPOIRequest=>诊断请求。

我正在寻找一种方法来知道我是哪种形式的团体,以及在它之上的团体

在下面的示例中,该按钮位于Group:DiagnosisRequest表单中,高于此表单的是SaleToPOIRequest。这就是为什么预期结果是这样的:SaleToPOIRequest.DiagnosisRequest或SaleToPPOIRequest=>诊断请求。

<div class="request-form" formGroupName="SaleToPOIRequest">
<div formGroupName="DiagnosisRequest">
<table>
<thead>
<tr>
<td>
<span>DiagnosisRequest</span>
</td>
<td class="form-buttons">
<button color="primary" (click)='getFormPosition' mat-raised-button>Add Field</button>
<button color="primary" mat-raised-button>Add Category</button>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<mat-form-field>
<mat-label>HostDiagnosisFlag</mat-label>
<input formControlName="HostDiagnosisFlag" matInput>
</mat-form-field>
</td>
</tr>
</tbody>
</table>
</div>
</div>

这是我的ts,以防你想知道:

public DiagnosisRequestForm: FormGroup = new FormGroup({
SaleToPOIRequest: new FormGroup({
DiagnosisRequest: new FormGroup({
HostDiagnosisFlag: new FormControl(''),
}) 
})
}) 

坦率地说,我没有这个问题的答案,因为我认为不可能以一种干净的方式来做这件事。

因此,对我来说,解决方案是对其进行整体返工并递归执行,这样添加另一个formControl/组将更容易,并在TS中完成,之后只需再次更新或生成整个html。

以下是引用递归生成问题的问题:

生成表格槽回路

从表单生成表格

// you can use an id on div with DiagnosisRequest
in JS
var el = document.getElementById('DiagnosisRequest')
window.alert(el.offsetLeft)
//for X,Y position
const elbc = el.getBoundingClientRect()
window.alert(elbc.x+" "+elbc.y) 
//if you are using ts and angular 
@ViewChild("DiagnosisRequest", { static: false }) dr: ElementRef;
//then you can get this.dr.nativeElement.offsetLeft

最新更新