要创建一个多级问题答案层次结构的递归组件,可以使用Angular的组件嵌套和递归调用的特性。
首先,创建一个组件,用于显示问题和答案。我们将其命名为"question-answer"(可以根据实际需要更改名称)。
question-answer.component.ts:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-question-answer',
template: `
{{ question }}
{{ answer }}
0">
`,
styles: [
'.question { font-weight: bold; }',
'.answer { margin-left: 20px; }'
]
})
export class QuestionAnswerComponent {
@Input() question: string;
@Input() answer: string;
@Input() subQuestions: any[];
}
在上述代码中,我们使用了Angular的ngIf和ngFor指令来处理递归问题。如果子问题的数组(subQuestions)不为空,则使用*ngFor循环创建嵌套的"question-answer"组件。
接下来,创建一个父组件,用于传递问题和答案的数据给"question-answer"组件。我们将其命名为"app.component"。
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
questions = [
{
question: 'Question 1',
answer: 'Answer 1',
subQuestions: [
{
question: 'Sub Question 1.1',
answer: 'Sub Answer 1.1',
subQuestions: []
},
{
question: 'Sub Question 1.2',
answer: 'Sub Answer 1.2',
subQuestions: []
}
]
},
{
question: 'Question 2',
answer: 'Answer 2',
subQuestions: [
{
question: 'Sub Question 2.1',
answer: 'Sub Answer 2.1',
subQuestions: [
{
question: 'Sub Sub Question 2.1.1',
answer: 'Sub Sub Answer 2.1.1',
subQuestions: []
}
]
}
]
}
];
}
在上述代码中,我们在父组件中定义了一个包含问题、答案和子问题数组的questions数组。然后使用*ngFor循环来创建多个"question-answer"组件,并传递相应的数据。
最后,在app.module.ts中引入和声明两个组件:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { QuestionAnswerComponent } from './question-answer/question-answer.component';
@NgModule({
declarations: [
AppComponent,
QuestionAnswerComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
在上述代码中,我们将"AppComponent"和"QuestionAnswerComponent"声明为模块的组件。
现在,你可以在app.component.html中使用
希望对你有所帮助!