我有一个组件,我将用它作为加载到多选题的外壳。下面是如何将组件成立至今Angular2:你如何正确地绑定到嵌套数据?
组件
import { Component } from '@angular/core';
export class Answers{
id: string;
answer: string;
}
const answers: Answers[] = [
{
id: 'exp01q',
answer: 'Its fine as is.'
},
{
id: 'exp02q',
answer: 'I want to make minor adjustments.'
},
{
id: 'exp03q',
answer: 'I want to change my image'
},
{
id: 'exp04q',
answer: 'Ive never wanted to use a particular image until now.'
}
];
@Component({
moduleId: module.id,
selector: 'multi-radio-btn',
templateUrl: 'multi-rad-btn.component.html',
styleUrls: ['multi-rad-btn.component.css']
})
export class MultiRadioBtnShell {
question = 'How do you feel about your current image?';
id = 'exp-img-q';
name = 'exp-ques1';
ans = answers;
}
HTML模板
<h3>radio button shell</h3>
<div class="row justify-content-center">
<fieldset [attr.id]='id' class="card col-8 justify-content-center">
<label class="ques-title">
{{question}}
</label>
<div class="row answer-row-section justify-content-center">
<div *ngFor="let answers of ans" class="col col-12 answer-row justify-content-center">
<div class="col justify-content-center">
<input type="radio"
[attr.id]="answers.id"
[attr.name]="name"
[attr.value]="answers.answer" hidden />
<label [attr.for]="answers.id" class="col ques-ans-title" style="background-color: #4b73a0;">
{{answers.answer}}
</label>
</div>
</div>
</div>
</fieldset>
</div>
它的成立是现在这个样子的原因是因为这样,我试图在第一次做没有工作,所以我去了英雄之旅教程跟随他们如何加载所有的英雄。问题来自未定义的答案。所以我就像他们做英雄一样操纵那部分,只是为了做一些我能够遵循的事情,以确保我得到了如何加载的机制。
我试图做的是与此
// I had this right above the component
export class ExpQ{
question: string;
id: string;
name: string;
answers:[
{
id: string;
answer: string;
}
]
}
// I had this in the component's class
export const expq: ExpQ[] = [
{
question: 'How do you feel about your current image?',
id: 'exp-img-q',
name: 'exp-ques1',
answers:[
{
id: 'exp01q',
answer: 'Its fine as is.'
},
{
id: 'exp02q',
answer: 'I want to make minor adjustments.'
},
{
id: 'exp03q',
answer: 'I want to change my image'
},
{
id: 'exp04q',
answer: 'Ive never wanted to use a particular image until now.'
}
]
}
]
我与调用它在HTML中的原始的方式
{{} expq.question},{{} expq.name },{{} expq.answers.id},{{expq.answers.answer}}等
起初只加载它工作得很好的问题,但我到了answers:
部分它开始打破。我遇到了这个https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol,看到addresses:
部分的语法与我需要构建数据的方式非常相似。所以我把所有的东西重新制作成类似的东西。我仍然没有运气让它工作。
最终,我将通过父组件发送问题@input
和@output
以及我遇到的其他一些技巧。但在我甚至想到我需要处理如何将数据全部放入一个源中以便正确地读取嵌套的数据位之前,我遇到的所有例子都是简单的单层数据,所以我不确定我需要使用的语法。我该如何做这项工作?
确定我看到如何继续下去,我把它的语法,我试图做到这一点是确定然后,我只需要调用这样的那些部分的原始的方式? – Optiq
是的,把它想成扁平的零件。当您遇到错误时,您正在尝试访问数组而无需编入索引。例如,如果您尝试过{{expq.answers [0] .answer}},您可以看到第一个答案(如果存在)。但不是硬编码,我假设你想像你刚才所说的那样迭代它。 – DeezCashews
嗯。我刚回到它并回到'字符串未定义'错误。 – Optiq