<mat-form-field>
<mat-label>First Name</mat-label>
<input matInput formControlName="firstName" />
</mat-form-field>
输出这个可憎的东西:
<div class="mat-form-field-infix ng-tns-c125-1">
<input _ngcontent-sfi-c379="" matinput="" formcontrolname="firstName" required="" class="mat-input-element mat-form-field-autofill-control ng-tns-c125-1 cdk-text-field-autofill-monitored ng-dirty ng-touched ng-invalid" ng-reflect-required="" ng-reflect-name="dealerName" id="mat-input-0" aria-required="true"><span class="mat-form-field-label-wrapper ng-tns-c125-1">
<label class="mat-form-field-label ng-tns-c125-1 ng-star-inserted mat-empty mat-form-field-empty" ng-reflect-disabled="true" id="mat-form-field-label-1" ng-reflect-ng-switch="true" for="mat-input-0" aria-owns="mat-input-0">
<mat-label _ngcontent-sfi-c379="" class="ng-tns-c125-1 ng-star-inserted">First Name</mat-label>
</label>
</span>
</div>
您将注意到输出的这一部分:id="mat-input-0"
。我真的希望它输出id="firstName"
,或者保持id不变,并向输入添加一个name属性(例如name="firstName"
(。我可以手动将id(或name(属性添加到角度标记中的输入字段,它会正确呈现,但我真的不想为应用程序中的所有4000个输入字段显式添加它。
我为什么要这个?因为我的表单自动填充(用于测试数据(只能查看名称或id字段,我不想一直都是非常具体的。
您可以使用自定义属性指令,并将现有的formControlName
属性重新用作选择器,以避免在所有4000个输入中添加id
或name
属性:
@Directive({
selector: 'input[formControlName]'
})
export class MyFormControlNameDirective {
constructor(
elementRef: ElementRef<HTMLElement>,
@Attribute('formControlName') name: string
) {
const el = elementRef.nativeElement;
if (!el.hasAttribute('name')) {
el.setAttribute('name', name);
}
}
}