我正试图在我的项目中用垫子手风琴显示常见问题列表.我有一个静态数组,我已将其集成到Form数组中.当我在我的模板中交互Form数组时,我没有得到显示,并且我得到了错误Cannot read properties of null (reading 'value')
.你知道为什么吗?你有什么解决方案吗?我在Stackblitz的工作:https://stackblitz.com/edit/angular-una717?file=app%2Fexpansion-overview-example.ts,app%2Fexpansion-overview-example.html
我的代码:
// HTML
<form [formGroup]="faqsForm">
<div formArrayName="faqsFormArray">
<mat-accordion class="faqs-accordion">
<mat-expansion-panel
class="faqs-expansion-panel"
*ngFor="let faq of faqsForm.get('faqsFormArray').controls; index as i"
(opened)="panelOpenState = true"
(closed)="panelOpenState = false"
>
<!-- Header -->
<mat-expansion-panel-header class="faqs-expansion-panel-header">
<!-- Question -->
<mat-panel-title class="faqs-panel-title">
<!-- Section-->
<mat-panel-description class="faqs-panel-description">
{{ faq.get('section').value }}
</mat-panel-description>
{{ faq.get('question').value }}
</mat-panel-title>
</mat-expansion-panel-header>
<!-- Content -->
<p class="faqs-panel-content">{{ faq.get('answer').value }}</p>
</mat-expansion-panel>
</mat-accordion>
</div>
</form>
// TS
// ********** DECLARATIONS **********//
// Variables for the accordion
public panelOpenState = false;
// For the form
public faqsForm: FormGroup;
public faqsFormArray: FormArray;
public displayFaqsItems = [
{
key: '1',
section: 'Verwaltung',
question: 'Test1',
answer: 'dsdsddssddssd',
},
{
key: '2',
section: 'Absatz',
question: 'Test2',
answer: 'DSDSSDSDSDSDSDSDSD',
},
{
key: '3',
section: 'Beschaffung',
question: 'Test3',
answer: 'dghsghdsghsdghgsdhsdghsdghsdgsdghsdghsdgds',
},
{
key: '4',
section: 'Finanzen',
question: 'Test4',
answer: 'fdfdfdfdsssdsdfsdfsdf',
},
];
constructor(
private formBuilder: FormBuilder) {}
ngOnInit() {
// To initialize forms
this.initForm();
// Call formRowsData
this.displayFormElements(this.displayFaqsItems);
}
// Creation of the faqs form
initForm() {
// General
this.faqsForm = this.formBuilder.group({
faqsFormArray: this.formBuilder.array([]),
});
}
/**
* To add form structure in the faqs
*/
public formStructure() {
const formArray = this.faqsForm.get('faqsFormArray') as FormArray;
const start =
this.faqsFormArray && this.faqsFormArray !== null
? this.faqsFormArray.controls.length
: 0;
for (let i = start; i < start + 1; i++) {
const rowData = {
key: new FormControl(`new-${i}`),
section: new FormControl(''),
question: new FormControl(''),
answer: new FormControl(''),
};
const createRow = this.formBuilder.group(rowData);
formArray.push(createRow);
}
this.faqsFormArray = formArray;
}
/**
* To show formElements
* @param accordionRows any
*/
public displayFormElements(accordionRows: any) {
const formArray = this.faqsForm.get('faqsFormArray') as FormArray;
const createRow = this.formBuilder.group(accordionRows);
formArray.push(createRow);
this.faqsFormArray = formArray;
}