在我的Angular2应用程序中,我需要显示编辑器可以创建的问题列表。在每个问题下面可以有0-n个答案(选项 - 例如'是',' no',' 5'等)。所以我需要从QuestionComponent中加载AnswerComponent。
但是,每个答案都可以有0-1个问题(后续问题)。这意味着我还必须从AnswerComponent中加载QuestionComponent。
这是一个掠夺者:http://plnkr.co/edit/1itBVtDu8TD8Etxo4JZh
QuestionComponent(简化):
@Component({
selector: 'copyright-question',
template: `
<div class="col-md-8">
<strong>{{ question?.content }}</strong>
<div class="row-actions">
<span *ngIf="!question?.isAnswer" class="addAnswer"><button (click)="onAddAnswer()">Add Answer</button></span>
</div>
</div>,
<li *ngFor="let answer of question.answers">
<copyright-answer [answer]="answer"></copyright-answer>
</li>
`,
directives: [AnswerComponent]
})
AnswerComponent(简化):
@Component({
selector: 'copyright-answer',
template: `
<ul class="col-md-12">
<li><strong>{{ answer.answerTxt }}</strong></li>
<li>
<div class="row-actions">
<span>
<span><button (click)="onQuestionSave()">Add follow-up question</button></span>
</span>
</div>
</li>
<!-- Follow Up Question -->
<li>
<copyright-question [question]="copyrightQuestion"></copyright-question>
</li>
</ul>
`,
directives: [QuestionComponent]
})
经过3天的研究,我知道这是循环依赖。无论如何,我不知道如何解决这个问题。我需要提供任意序列长度的问题和答案。我尝试了前向引用但仍然有以下错误消息:
异常:意外的指令值&#39; undefined&#39;在组件的视图&#39; AnswerComponent&#39;
仅供参考:该应用程序是离子应用程序的后端。如果用户必须回答问题并根据他选择的内容,将会有后续问题或结果(技术上也是一个问题)。
如果这个问题重复,请随时向我展示这个问题的答案!但是,我无法找到一个解决方案,该解决方案使用嵌套的组件。
非常感谢!!!
答案 0 :(得分:1)
在插值内尝试Elvis
运算符?.
。
{{ answer?.answerTxt }}
如果answer
是假的(未定义,null等),则无法访问answerTxt
成员。
answer
将null
,直到您得到回复。
答案 1 :(得分:1)
/**
* Created by Brudus on 11/06/16.
*/
import {Component, OnInit, Input, forwardRef} from "@angular/core";
import {Question} from "./question";
import {Answer} from "./answer";
import {QuestionComponent} from "./question.component";
@Component({
selector: 'copyright-answer',
template: `
<ul *ngIf="answer" class="col-md-12">
<li><strong>{{ answer.answerTxt }}</strong></li>
<li>
<div class="row-actions">
<span>
<span><button (click)="onQuestionSave()">Add follow-up question</button></span>
</span>
</div>
</li>
<!-- Follow Up Question -->
<li *ngIf="copyrightQuestion">
<copyright-question [question]="copyrightQuestion"></copyright-question>
</li>
</ul>
`,
directives: [forwardRef(() => QuestionComponent)]
})
export class AnswerComponent implements OnInit {
@Input() answer: Answer;
copyrightQuestion: Question = null;
constructor() {}
ngOnInit() {
}
onQuestionSave() {
//content: string, isAnswer: boolean, answers?: Answer[],
// isRoot?: boolean, parentQuestion?: string
const question: Question = new Question('Follow-up question', false, null,
false, null);
this.copyrightQuestion = question;
}
}