从组件到使用 ngModels 查看的带有数组的角度绑定对象 [英] Angular binding object with array from component to view with ngModels

查看:24
本文介绍了从组件到使用 ngModels 查看的带有数组的角度绑定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在视图上绑定模型,但在提交表单时出现问题:我没有数组,但有很多属性.

组件:

导出类 QuizFormAddQuestionComponent 实现 OnInit {公开问题:问题;构造函数(){this.question = new Question();}ngOnInit() {this.question.setModel({ 问题:'测试'});this.question.setAnswers(3);}创建问题(形式){控制台日志(表单值);}}

我的模板:

<hello name="{{ name }}"></hello><div class="row"><div class="col-sm-1"></div><div class="col-sm-10"><form #form="ngForm" (ngSubmit)="createQuestion(form)" class="mt-4"><div class="form-row"><div class="form-group col-md-12"><label for="question" class="col-form-label">问题</label><输入类型="文本"类=形式控制"id="问题"placeholder="输入您的问题..."名称=问题"[ngModel]="问题.问题"需要>

<div class="form-group row" *ngFor="let answer of question.answers; let i = index;"><div class="col-sm-12"><div class="form-check"><label class="form-check-label"><input class="form-check-input"类型=复选框"id="answer-value-{{i}}"[ngModel]="question.answers[i].value"name="answers[{{i}}].value">回答 {{ i }}

<输入类型="文本"类=形式控制"id="answer-text-{{i}}"[ngModel]=question.answers[i].textname="answers[{{i}}].text">{{ answer.getManipulateObjet() }}

<div class="form-row"><div class="form-froup col-md-12 text-right"><button type="submit" class="btn btn-primary">添加问题</button>

</表单>

question.ts(模型)

import { Answer } from "./answer";出口类问题{构造函数(私人问题:字符串 = '',私人答案:任何[] = [],私人更多信息:字符串 = '',私人难度:数字 = 0,) {}设置模型(对象){Object.assign(this, obj);}添加答案(){让 new_answer = new Answer();new_answer.setModel({ text: 'test', value: false });this.answers.push(new_answer);}setAnswers(number_answers) {for (let i = 0; i 

answer.ts(模型)

导出类答案{构造函数(私人文本:字符串 = '',私有值:boolean = false,) {}设置模型(对象){Object.assign(this, obj);}getManipulateObjet() {return '=== call getManipulateObjet() 例如:在操作对象、计数值属性、concat 等之后返回更多信息... ===';}获取计数(){//....}getInspectMyObject() {//...}}

初始对象:

提交后的控制台:

提交后我想要与初始对象相同的东西(与更新数据相同的结构),提交前后相同的数据结构

我认为我试过这个,但它不起作用:

<div class="col-sm-12"><div class="form-check"><label class="form-check-label"><input class="form-check-input"类型=复选框"id="answer-value-{{i}}"[ngModel]="answer.value"name="answer[{{i}}].value">回答 {{ i }}

<输入类型="文本"类=形式控制"id="answer-text-{{i}}"[ngModel]=answer.textname="answer[{{i}}].text">{{ answer.getManipulateObjet() }}

我在 [ngModel]="answer.text" 的 *ngFor [ngModel]=question.answers[i].text 中进行了转换,但我有同样的问题...

我从不同的帖子中尝试了很多东西:Angular 2 form with array对象输入Angular 2 - 2 Way Binding在 NgFor 中使用 NgModel

但总是有很多属性而没有数组

我想在没有反应形式的情况下做到这一点,只有模板驱动

<块引用>

演示:

https://angular-by7uv1.stackblitz.io/

我想使用与我的对象answer"不同的函数,例如:answer.getInformation()、getCount()、getInspectMyObject() 等.在我看来,仅迭代我的对象.此功能由我的模型答案"提供,以便在我看来有一个干净的代码.我想在 *ngFor 中使用我的模型中的许多函数.如果我使用反应式形式,我不能使用与我的模型不同的函数,因为我的父对象和我的孩子之间的链接"被破坏了.

<块引用>

已解决

https://fom-by-template-driven.stackblitz.io

解决方案

问题是,无论指定什么 input 名称,它都会被视为纯文本.不应引用任何ObjectArray.但稍加修改,就有机会获得与更新数据相同的数据结构.

所有元素都以一种方式绑定,所以要进行双向绑定.所以每当 input 值改变时,绑定的 element 值就会更新.

 [(ngModel)]="question.question"

使用模板驱动的表单进行验证

...<button [disabled]="!form.valid"

现在这些值已经过验证&在变量question中更新.不需要从表单中获取值,使用更新的对象question来创建问题.

createQuestion() {console.log(this.question);}

查看应用程序中的结果

I tried to bind my model on my view, but I have a problem when I submit my form : I don't have an array, but many property.

component :

export class QuizFormAddQuestionComponent implements OnInit {
    public question: Question;

    constructor() {
        this.question = new Question();
    }

    ngOnInit() {
        this.question.setModel({ question: 'test' });
        this.question.setAnswers(3);
    }

    createQuestion(form) {
        console.log(form.value);
    }

}

my template :

<hello name="{{ name }}"></hello>

<div class="row">
    <div class="col-sm-1"></div>
    <div class="col-sm-10">

        <form #form="ngForm" (ngSubmit)="createQuestion(form)" class="mt-4">
            <div class="form-row">
                <div class="form-group col-md-12">
                    <label for="question" class="col-form-label">Question</label>
                    <input type="text"
                           class="form-control"
                           id="question"
                           placeholder="Enter your question..."
                           name="question"
                           [ngModel]="question.question"
                           required>
                </div>
            </div>
            <div class="form-group row" *ngFor="let answer of question.answers; let i = index;">
                <div class="col-sm-12">
                    <div class="form-check">
                        <label class="form-check-label">
                            <input class="form-check-input"
                                   type="checkbox"
                                   id="answer-value-{{i}}"
                                   [ngModel]="question.answers[i].value"
                                   name="answers[{{i}}].value">
                            Answer {{ i }}
                        </label>
                    </div>
                    <input type="text"
                           class="form-control"
                           id="answer-text-{{i}}"
                           [ngModel]=question.answers[i].text
                           name="answers[{{i}}].text">
                           {{ answer.getManipulateObjet() }}
                </div>
            </div>
            <div class="form-row">
                <div class="form-froup col-md-12 text-right">
                    <button type="submit" class="btn btn-primary">Add question</button>
                </div>
            </div>
        </form>
    </div>
</div>

question.ts (model)

import { Answer } from "./answer";

export class Question {

    constructor(private question: string          = '',
                private answers: any[]            = [],
                private more_informations: string = '',
                private difficulty: number        = 0,) {
    }

    setModel(obj) {
        Object.assign(this, obj);
    }

    addAnswer() {
        let new_answer = new Answer();

        new_answer.setModel({ text: 'test', value: false });

        this.answers.push(new_answer);
    }

    setAnswers(number_answers) {
        for (let i = 0; i < number_answers; i++) {
            this.addAnswer();
        }

        console.log(this);
    }

}

answer.ts (model)

export class Answer {

    constructor(private text: string  = '',
                private value: boolean = false,) {
    }

    setModel(obj) {
        Object.assign(this, obj);
    }

    getManipulateObjet() {
      return '=== call getManipulateObjet() for example : return more information after manipulating object, count value properties, concat, etc... ===';
    }

    getCount() {
      // ....
    }

    getInspectMyObject() {
      // ...
    }
}

initial object :

console after submit :

After the submit I would like the same things as the initial object (same structure with the data updated), the same data structure before and after submit

I tried this on in my view, but it doesn't work :

<div class="form-group row" *ngFor="let answer of question.answers; let i = index;">
    <div class="col-sm-12">
        <div class="form-check">
            <label class="form-check-label">
                <input class="form-check-input"
                       type="checkbox"
                       id="answer-value-{{i}}"
                       [ngModel]="answer.value"
                       name="answer[{{i}}].value">
                Answer {{ i }}
            </label>
        </div>
        <input type="text"
               class="form-control"
               id="answer-text-{{i}}"
               [ngModel]=answer.text
               name="answer[{{i}}].text">
               {{ answer.getManipulateObjet() }}
    </div>
</div>

I transform in the *ngFor [ngModel]=question.answers[i].text by [ngModel]="answer.text", but I have the same problem...

I tried many things from differents posts : Angular 2 form with array of object inputs, Angular 2 - 2 Way Binding with NgModel in NgFor

But always many properties and no array

I would like to do this without reactive form, only template driven

Demo:

https://angular-by7uv1.stackblitz.io/

I would like to use different function from my object 'answer', for example : answer.getInformation(), getCount(), getInspectMyObject() etc.. to iterate on my object only, in my view. This function is provided by my model 'Answer' to have a clean code in my view. I would like use many functions from my model in the *ngFor. If I use the reactive form, I can't use different function from my model because the "link" between my parent object and my childs is broken.

SOLVED

https://fom-by-template-driven.stackblitz.io

解决方案

The problem is, whatever the input name specified, it will be considered as just text. Should not reference any Object or Array.But with slight modifications, there is a chance to obtain the same data structure with updated data.

All elements are binded in one way, so make it two way binding. So whenever input value changes, The binded element value updates.

 [(ngModel)]="question.question"

Use template driven form for validation

<form #form="ngForm" (ngSubmit)="createQuestion()" class="mt-4">
...
<button [disabled]="!form.valid"  

Now the values are validated & updated in the variable question.There is no need to get the value from form, use the updated object question to create question.

createQuestion() {
        console.log(this.question);
    }

View the results in worked out App

这篇关于从组件到使用 ngModels 查看的带有数组的角度绑定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆