强制 mat-form-field 输出名称或 ID

forcing mat-form-field to output a name or id

<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="firstName"。我可以手动将 id(或名称)属性添加到angular 标记中的输入字段并正确呈现,但我真的不想为整个应用程序的所有 4000 个输入字段显式添加它。

我为什么要这个?因为我的表单自动填充(用于测试数据)只能查看 name 或 id 字段,我不想一直都这么具体。

您可以使用自定义 attribute directive 并重新使用现有的 formControlName 属性作为选择器,以避免向所有 4000 个输入添加 idname 属性:

@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);
        }
    }
}