我有一个用于计算嵌套数组的Angular 的简单指令:
import { AfterViewInit, Directive, Input, OnDestroy } from '@angular/core';
@Directive({
selector: '[rhsNestedArrayCounter]',
exportAs: 'rhsNestedArrayCounter'
})
export class NestedArrayCounterDirective implements AfterViewInit, OnDestroy {
static nextIndex = -1;
@Input() appCounter: number | string = '';
index;
constructor() {
this.index = NestedArrayCounterDirective.nextIndex++;
}
ngAfterViewInit(): void {
if (typeof this.appCounter === 'string') {
return;
}
NestedArrayCounterDirective.nextIndex = this.appCounter;
}
ngOnDestroy(): void {
NestedArrayCounterDirective.nextIndex = -1;
}
}
我在我的html中这样使用它,让我们称之为FormComponent:
<form [formGroup]="detailForm" class="form-container">
<ng-container rhsNestedArrayCounter="0">
<div *ngFor="let section of sections; let sectionIndex = index">
<div class="section">
<div class="section-content">
<h3>{{ section.title }}</h3>
<div formArrayName="responses">
<div
*ngFor="
let questionWithAnswer of section.questionsWithAnswers;
let questionIndex = index
">
<div class="question">
<div
rhsNestedArrayCounter
#counter="rhsNestedArrayCounter"
class="question-content"
[formGroupName]="counter.index">
<h4>
{{
questionWithAnswer.questionDescription
| textReplacer: '#EmployeeName':employeeName
}}
</h4>
<div>
<mat-form-field
color="accent"
id="sectionAnswer-{{ counter.index }}">
<textarea
matInput
placeholder="Answer"
formControlName="text"
name="text"
id="sectionAnswerInput-{{ counter.index }}"
[required]="questionWithAnswer.isRequired"
cdkTextareaAutosize
#autosize="cdkTextareaAutosize"
cdkAutosizeMinRows="2"
cdkAutosizeMaxRows="6"></textarea>
<mat-error
*ngIf="responses.controls[counter.index].get('text')?.errors?.['required']"
id="sectionAnswerError"
>Required field</mat-error
>
<mat-error
*ngIf="responses.controls[counter.index].get('text')?.errors?.['minlength']"
id="sectionAnswerMinLengthError"
>Min 2 characters</mat-error
>
<mat-error
*ngIf="responses.controls[counter.index].get('text')?.errors?.['maxlength']"
id="sectionAnswerMaxLengthError"
>Max 6000 characters</mat-error
>
<mat-error
*ngIf="responses.controls[counter.index].get('text')?.errors?.['pattern']"
id="sectionAnswerSpecialCharactersPatternError"
>Only letters, numbers, and some punctuation marks are
allowed.</mat-error
>
</mat-form-field>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</ng-container>
</form>
当我有一次在我的PageComponent中使用FormComponent时,一切都运行得很好,现在我有了一个PageTwoComponent,我需要多次使用FormComponent,因为这个计数器是全局的,所以我得到了关于索引的错误.例如,表单有15个问题,我得到了索引16的错误,因为当开始计算第二个FormComponent时,它从16开始,因为第一个FormComponent在15中完成(使用父组件中FormComponent的两倍).
所以我想也许可以在指令中使用字典,其中我 for each 组件都有一个唯一的索引,每个名称都有一个唯一的索引,但我不知道如何实现这一点,或者可能是另一个 idea (我是一名C#开发人员),欢迎任何帮助.