- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我有一个 Mailtype 类型的 typescript 对象,如下所示:
export class Mailtype {
constructor(
public name?: string,
public locale?: string,
public email?: string,
public properties? : Property[]
) { }
}
它的“属性”字段是属性类型的数组:
export class Property {
constructor(
public name?: string,
public type?: string,
public example?: string,
public required?: boolean,
public masked?: boolean
) { }
}
现在在我的组件中我有一个 Mailtype 对象并且 html 有一个表单元素用于编辑和添加到 Mailtype 的属性数组:
<form>
<tr *ngFor="let property of model.properties; let i=index">
<td>
<input type="text" [(ngModel)]="property.name" required>
</td>
</tr>
<button (click)="onAddProperty()">Add property</button>
</form>
组件:
export class MailtypeComponent {
model : Mailtype;
constructor() {
this.model = new Mailtype('','','',[]);
this.model.properties.push(new Property());
}
onAddProperty() {
this.model.properties.push(new Property());
}
}
我想知道我是否不允许使用 [(ngModel)] 链接到数组中数组元素的引用“属性”,尤其是在我迭代数组的同时?因为上面的代码会抛出如下错误:
ORIGINAL EXCEPTION: If ngModel is used within a form tag, either the name attribute must be set
or the form control must be defined as 'standalone' in ngModelOptions.
Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
因此建议我使用 [ngModelOptions]="{standalone: true}"
或向 html 添加名称字段。看起来 [ngModelOptions]="{standalone: true}"
在这种情况下有效。 standalone: true
实际上是什么意思,因为我找不到任何关于它的文档?
最佳答案
使用 @angular/forms
当你使用 <form>
标记它会自动创建一个 FormGroup
.
对于每个包含的 ngModel
已标记 <input>
它将创建一个 FormControl
并将其添加到 FormGroup
中在上面创建;这个FormControl
将被命名为FormGroup
使用属性 name
.
例子:
<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
<span>{{ f.controls['firstField']?.value }}</span>
</form>
说到这里,您的问题的答案如下。
当您将其标记为 standalone: true
时这不会发生(它不会被添加到 FormGroup
)。
引用:https://github.com/angular/angular/issues/9230#issuecomment-228116474
关于 Angular 2 : use [(ngModel)] with [ngModelOptions] ="{standalone: true}" to link to a reference to model's property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38365761/
我是一名优秀的程序员,十分优秀!