Angular 将组件中的数组绑定 object 以使用 ngModels 查看
Angular binding object with array from component to view with ngModels
我试图在我的视图上绑定我的模型,但是我在提交表单时遇到了问题:我没有数组,但是很多 属性.
分量:
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);
}
}
我的模板:
<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(型号)
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(型号)
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() {
// ...
}
}
初始 object :
提交后控制台:
提交后我想要与初始object相同的东西(更新数据的相同结构),提交前后相同的数据结构
我在我看来试过这个,但它不起作用:
<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>
我在 *ngFor [ngModel]=question.answers[i].text 中通过 [ngModel]="answer.text" 进行转换,但我有同样的问题...
我从不同的帖子中尝试了很多东西:Angular 2 form with array of object inputs,
但总是有很多属性而没有数组
我想在没有反应形式的情况下做到这一点,只有模板驱动
Demo:
https://angular-by7uv1.stackblitz.io/
我想使用与 object 'answer' 不同的函数,例如:answer.getInformation()、getCount()、getInspectMyObject() 等来迭代我的object 只是,在我看来。此功能由我的模型 'Answer' 提供,以便在我看来有一个干净的代码。我想在 *ngFor 中使用我的模型中的许多函数。如果我使用反应形式,我不能使用与我的模型不同的函数,因为我的 parent object 和我的孩子之间的 "link" 坏了。
SOLVED
你可以这样做:-
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormArray, FormControl} from '@angular/forms';
@Component({
selector: 'form-component',
template: `
<form [formGroup]="formGroup">
<div formArrayName="inputs" *ngFor="let control of formArray; let i = index;">
<input placheholder="Name please" formControlName="{{i}}"/>
</div>
</form>
<button (click)="addInput()">Add input</button>
`
})
export class FormComponent implements OnInit{
formGroup: FormGroup;
contructor() {
}
ngOnInit(){
this.formGroup = new FormGroup({
inputs: new FormArray([
new FormControl("Hello"),
new FormControl("World"),
]);
});
}
get formArray() {
return this.formGroup.get('inputs').controls
}
addInput(){
this.formArray.push(new FormControl("New Input"));
}
}
我看到您在 html 模板中使用了 [ngModel]
。这只会绑定输入以绑定输出,您也需要使用 [(ngModel)]
。这是使用 ngModel
的常规方式。我发现您的代码中还有一个错误,即 name="answer[{{i}}].value"
这里的名称是值应该是常量,您将其作为变量赋予它正确的书写方式是 name="{{answer[i].value}}"
使用当前的 Angular 模板驱动表单,无法实现以下场景。
Angular 团队 LINK 提出了一个问题。
它需要大量返工,因为模板驱动的表单使用 ngModel 。 Angular 表单正朝着反应式方法发展,在最近的功能中我没有看到添加此功能。
请为此使用 React 表单 formArrayName
足以帮助获得所需的结果。
问题是,无论指定什么 input
名称,它都将被视为纯文本。不应引用任何 Object
或 Array
。但稍作修改,就有机会获得与更新数据相同的数据结构。
所有元素都以一种方式绑定,所以使其成为双向绑定。因此,每当 input
值发生变化时,绑定的 element
值就会更新。
[(ngModel)]="question.question"
使用template driven form
进行验证
<form #form="ngForm" (ngSubmit)="createQuestion()" class="mt-4">
...
<button [disabled]="!form.valid"
现在变量 question
中的值已验证和更新。无需从表单中获取值,使用更新后的对象 question
创建问题。
createQuestion() {
console.log(this.question);
}
academicYearTerms: [{
term_name: {
type: String,
default: " "
},
term_end: {
type: Date,
},
term_start: {
type: Date,
},
}]
在节点js中声明
adminpageform = new FormGroup({
start_date: new FormControl(''),
end_date: new FormControl(''),
acadyr_shortcode: new FormControl(''),
no_terms: new FormControl(''),
term_name: new FormControl(''),
term_end: new FormControl(''),
term_start: new FormControl(''),
TermsId: new FormControl('')
});
在 ts 中声明
如何在表单控件中存储对象值数组
我试图在我的视图上绑定我的模型,但是我在提交表单时遇到了问题:我没有数组,但是很多 属性.
分量:
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);
}
}
我的模板:
<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(型号)
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(型号)
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() {
// ...
}
}
初始 object :
提交后控制台:
提交后我想要与初始object相同的东西(更新数据的相同结构),提交前后相同的数据结构
我在我看来试过这个,但它不起作用:
<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>
我在 *ngFor [ngModel]=question.answers[i].text 中通过 [ngModel]="answer.text" 进行转换,但我有同样的问题...
我从不同的帖子中尝试了很多东西:Angular 2 form with array of object inputs,
但总是有很多属性而没有数组
我想在没有反应形式的情况下做到这一点,只有模板驱动
Demo:
https://angular-by7uv1.stackblitz.io/
我想使用与 object 'answer' 不同的函数,例如:answer.getInformation()、getCount()、getInspectMyObject() 等来迭代我的object 只是,在我看来。此功能由我的模型 'Answer' 提供,以便在我看来有一个干净的代码。我想在 *ngFor 中使用我的模型中的许多函数。如果我使用反应形式,我不能使用与我的模型不同的函数,因为我的 parent object 和我的孩子之间的 "link" 坏了。
SOLVED
你可以这样做:-
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormArray, FormControl} from '@angular/forms';
@Component({
selector: 'form-component',
template: `
<form [formGroup]="formGroup">
<div formArrayName="inputs" *ngFor="let control of formArray; let i = index;">
<input placheholder="Name please" formControlName="{{i}}"/>
</div>
</form>
<button (click)="addInput()">Add input</button>
`
})
export class FormComponent implements OnInit{
formGroup: FormGroup;
contructor() {
}
ngOnInit(){
this.formGroup = new FormGroup({
inputs: new FormArray([
new FormControl("Hello"),
new FormControl("World"),
]);
});
}
get formArray() {
return this.formGroup.get('inputs').controls
}
addInput(){
this.formArray.push(new FormControl("New Input"));
}
}
我看到您在 html 模板中使用了 [ngModel]
。这只会绑定输入以绑定输出,您也需要使用 [(ngModel)]
。这是使用 ngModel
的常规方式。我发现您的代码中还有一个错误,即 name="answer[{{i}}].value"
这里的名称是值应该是常量,您将其作为变量赋予它正确的书写方式是 name="{{answer[i].value}}"
使用当前的 Angular 模板驱动表单,无法实现以下场景。 Angular 团队 LINK 提出了一个问题。
它需要大量返工,因为模板驱动的表单使用 ngModel 。 Angular 表单正朝着反应式方法发展,在最近的功能中我没有看到添加此功能。
请为此使用 React 表单 formArrayName
足以帮助获得所需的结果。
问题是,无论指定什么 input
名称,它都将被视为纯文本。不应引用任何 Object
或 Array
。但稍作修改,就有机会获得与更新数据相同的数据结构。
所有元素都以一种方式绑定,所以使其成为双向绑定。因此,每当 input
值发生变化时,绑定的 element
值就会更新。
[(ngModel)]="question.question"
使用template driven form
进行验证
<form #form="ngForm" (ngSubmit)="createQuestion()" class="mt-4">
...
<button [disabled]="!form.valid"
现在变量 question
中的值已验证和更新。无需从表单中获取值,使用更新后的对象 question
创建问题。
createQuestion() {
console.log(this.question);
}
academicYearTerms: [{
term_name: {
type: String,
default: " "
},
term_end: {
type: Date,
},
term_start: {
type: Date,
},
}]
在节点js中声明
adminpageform = new FormGroup({
start_date: new FormControl(''),
end_date: new FormControl(''),
acadyr_shortcode: new FormControl(''),
no_terms: new FormControl(''),
term_name: new FormControl(''),
term_end: new FormControl(''),
term_start: new FormControl(''),
TermsId: new FormControl('')
});
在 ts 中声明 如何在表单控件中存储对象值数组