如何从angular FormControl获取数据属性



我有一个类似bellow的表单

<form #f="ngForm">
<div >
<label 

for="governmentalPosition">
MasterAgentInCashDeskGovernmentalPosition
</label>
<input 
id="governmentalPosition"
name="governmentalPosition"
[attr.data-localization]="'MasterAgentInCashDeskGovernmentalPosition'"
type="text"
required
pInputText
maxlength="500"
#governmentalPositionControl="ngModel"                                       [(ngModel)]="model.governmentalPosition">

</div> 
</form>

<button   type="button" (click)="save(f)" >
submit
</button>

我使用这个ts或js方法

save(f: NgForm) {
Object.keys(f.controls).forEach(controlName => {
let rr = f.controls[controlName].errors;
//this how I can get the attr.data-localization
}
}

如何在angular app的ts文件或js文件中获取data属性

您可以使用不同的方法获得data attribute:

角道:

@ViewChild('governmentalPositionControl') input: ElementRef; 
//...
const dataValue = this.input.nativeElement.getAttribute("data-localization"); //--> get the data attribute

纯javascript:

const input = document.querySelector("#governmentalPosition"); //--> get the element
const dataValue = input.getAttribute("data-localization"); //--> get the data attribute

最新更新