【问题标题】:Angular2,Ionic2: How to do 2way binding for radio button in nested *ngfor using ngModel?Angular2,Ionic2:如何使用 ngModel 对嵌套 *ngfor 中的单选按钮进行 2way 绑定?
【发布时间】:2017-11-07 00:57:24
【问题描述】:

我有以下格式的 JSON 格式的 API。

我想以问题和选择格式的形式显示它。我正在尝试使用单选按钮显示选择。但我的ngModel 不工作。我想在我的 .ts 文件中使用 ngModel 访问所选选项的整个对象。

这是我的 ts 代码

export class Quiz implements OnInit {
    testcontents: Array<any>=[];
    choiceObj:any;

 constructor(public navCtrl: NavController, public navParams: NavParams,public http:Http) {}
     ngOnInit()
     {
       this.launchfunc();
     }
     launchfunc()
     {
    this.http.post('launchtest/getTestContent',this.launchtestobj).subscribe(resp=>{
         this.testcontents = resp.data.questions;
    });
     }

    selectChoice($event)
    {
      console.log("12312341234",event);
      console.log("obj",this.choiceObj);
    }

这是我的html代码

<ion-content padding>
<div *ngFor="let qContent of testcontents; let i = index">
    {{i+1}} {{qContent.questionText}}
    <div *ngFor="let choiceObj of qContent.choice">
        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choice' (ngModelChange)="selectChoice(choiceObj)" />
        <label [for]='choiceObj'>{{choiceObj.choiceText}}</label>
    </div>
</div>

这是上面代码的输出。 我不明白为什么 obj 未定义。 我对 ngModel 有疑问。我不明白我应该把我的 ngModel 放在什么位置,以及我应该如何访问 typescript 文件中的“choiceObj”。有人可以帮帮我吗。

【问题讨论】:

    标签: ionic2 angular-ngmodel angular2-directives radiobuttonlist ngfor


    【解决方案1】:

    模型是choiceObj.choice,在选择对象中不存在。 你需要用'choiceObj.choiceId'替换它

    <ion-content padding>
    <div *ngFor="let qContent of testcontents; let i = index">
        {{i+1}} {{qContent.questionText}}
        <div *ngFor="let choiceObj of qContent.choice">
            <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choiceId' (ngModelChange)="selectChoice(choiceObj)" />
            <label [for]='choiceObj'>{{choiceObj.choiceText}}</label>
        </div>
    </div>
    

    【讨论】:

    • 如果对您有帮助,能否请您将其标记为答案?
    • 非常感谢。有效。你能看看这个stackoverflow.com/questions/44455814/…
    • 如果您能将其标记为正确答案,我将不胜感激 :-)。我现在去看看。
    猜你喜欢
    • 2017-08-20
    • 2018-11-11
    • 2016-07-27
    • 2015-10-31
    • 2017-03-02
    • 2020-10-14
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多