Cal*_* Hu 34 typescript angular
假设我有一个类型为Mailtype的打字稿对象,如下所示:
export class Mailtype {
constructor(
public name?: string,
public locale?: string,
public email?: string,
public properties? : Property[]
) { }
}
Run Code Online (Sandbox Code Playgroud)
其"属性"字段是属性类型的数组:
export class Property {
constructor(
public name?: string,
public type?: string,
public example?: string,
public required?: boolean,
public masked?: boolean
) { }
}
Run Code Online (Sandbox Code Playgroud)
现在在我的组件中我有一个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>
Run Code Online (Sandbox Code Playgroud)
零件:
export class MailtypeComponent {
model : Mailtype;
constructor() {
this.model = new Mailtype('','','',[]);
this.model.properties.push(new Property());
}
onAddProperty() {
this.model.properties.push(new Property());
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道我是否不允许使用[(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}">
Run Code Online (Sandbox Code Playgroud)
所以它建议我使用或者[ngModelOptions]="{standalone: true}"
在html中添加一个名称字段.[ngModelOptions]="{standalone: true}"
在这种情况下它看起来像是有效的.为什么standalone: true
实际意味着因为我找不到任何关于它的文档?
zpu*_*pul 64
使用@angular/forms
时,您使用<form>
它会自动创建一个标签FormGroup
.
对于每个包含ngModel
标记的内容<input>
,它将创建一个FormControl
并将其添加到FormGroup
上面创建的内容中; 这FormControl
将被命名为FormGroup
using属性name
.
例:
<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
<span>{{ f.controls['firstField']?.value }}</span>
</form>
Run Code Online (Sandbox Code Playgroud)
说这个,你的问题的答案如下.
当你标记它时,standalone: true
这不会发生(它不会被添加到FormGroup
).
参考:https://github.com/angular/angular/issues/9230#issuecomment-228116474
对我来说代码:
<form (submit)="addTodo()">
<input type="text" [(ngModel)]="text">
</form>
Run Code Online (Sandbox Code Playgroud)
抛出错误,但我添加了name属性到输入:
<form (submit)="addTodo()">
<input type="text" [(ngModel)]="text" name="text">
</form>
Run Code Online (Sandbox Code Playgroud)
它开始起作用了.
归档时间: |
|
查看次数: |
86746 次 |
最近记录: |