我有一个选择列表,我想将其初始化为从服务器返回的保存值。但是,无论我尝试什么,都无法使用所选的值。
我正在使用Angular 2.2.0和Reactive Forms。
这是选择列表的值列表。
private categoryList: ICategory[] = [
new Category({ id: 1, name: 'Cat 1' }),
new Category({ id: 2, name: 'Cat 2' }),
new Category({ id: 3, name: 'cat 3' })
];
Run Code Online (Sandbox Code Playgroud)
保存的值为:
{ id: 1, name: 'Cat 1' }
Run Code Online (Sandbox Code Playgroud)
使用FormBuilder创建表单
this.itemForm = this.fb.group({
name: [null, Validators.required],
description: [null, Validators.required],
weight: [null, Validators.required],
dimensions: [null, Validators.required],
category: [null, Validators.required]
});
Run Code Online (Sandbox Code Playgroud)
然后用保存的数据初始化
(<FormGroup>this.itemForm)
.setValue({
name: item.name,
description: item.description,
weight: item.weight,
dimensions: item.dimensions,
category: item.category
}, …Run Code Online (Sandbox Code Playgroud) 我尝试基于其他字段验证表单字段值,所以我写了一个自定义验证器,当我试图获取其他字段时抛出错误我尝试了以下代码,请帮助我提前感谢
export class CreatesessionComponent implements OnInit {
eventform : FormGroup ;
constructor(private formBuilder: FormBuilder) {
}
ngOnInit() {
this.eventform = this.formBuilder.group({
eventname : new FormControl(''[Validators.required,Validators.pattern('[A-Za-z]+')]),
userlive : new FormControl('',[Validators.required,this.maxuser]),
totaluser :new FormControl('',[Validators.required,this.totaluser])
});
}
totaluser(control : FormGroup) : {[s:string ]: boolean} {
console.log(control.controls['eventname'].value)
// if(control.value > 20){
// return { total : true };
// }
return null;
}
Run Code Online (Sandbox Code Playgroud)
在控制台中出错,因为无法读取'eventname'未定义的属性
我遇到以下错误:
EXCEPTION: Uncaught (in promise): Error: Error in ./AccComponent class AccComponent - inline template:106:11 caused by: Cannot find control with name: 'det'
Run Code Online (Sandbox Code Playgroud)
我的formbuilder如下:
this.AccForm = this.fb.group({
accid: ['', Validators.required],
accnbr: ['', Validators.required],
cyc: this.fb.group({
cycid:['', Validators.required],
name:['', Validators.required],
description:['', Validators.required],
det: this.fb.group({
dcycid: ['', Validators.required],
status: ['', Validators.required],
})
})
});
Run Code Online (Sandbox Code Playgroud)
在我的模板中,当我试图获得formgroupname'dede'时,我得到了错误?
<div formGroupName="det">
<div class="row">
<div class="form-group>
<span><strong>Id</strong></span>
<input formControlName="dcycid" id="dcycid" type="number" class="form-control">
</div>
<div class="form-group">
<span><strong>status</strong></span>
<input formControlName="status" id="status" type="text" class="form-control">
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
备注'det'嵌套在第3级.
知道什么是错的吗?
谢谢.
/ …
试图在 Angular 2 中创建一个嵌套的动态表单。
形成骷髅
this.myForm= this.formBuilder.group({
programmes: this.formBuilder.array([this.initProgramme(),]),
});
initProgramme() {
return this.formBuilder.group({
tickets: this.formBuilder.array([this.initTicket(),])
});
}
initTicket() {
return this.formBuilder.group({
field1:''
});
}
Run Code Online (Sandbox Code Playgroud)
添加程序动态工作具有以下功能: -
addProgToForm(){
const control = <FormArray>this.myForm.get('programmes');
control.push(this.initProgramme());
}
Run Code Online (Sandbox Code Playgroud)
将票添加到程序抛出错误
addTicket(programme: any) {
const control = (<FormArray>this.myForm.get('programmes')).get(programme); // THROWS ERROR HERE
(<FormArray>control.get('tickets')).push(this.initTicket());
}
Run Code Online (Sandbox Code Playgroud)
在.get(programme)它说path.split 不是一个函数
PS - 'get(programme)' 中的 program 是要添加动态票证的 Program Form Array 的索引。它是从 *ngFor 正确检索的。示例:- 添加第一个程序的索引 0。
我试过几次迭代formArray,
这是这个案例的plunker链接https://plnkr.co/edit/4kiJF7cL5VKwn3KnvjvK?p=preview
我想要像这样的插件https://plnkr.co/edit/zg6nbFULl0WlTZ1sVn5h?p=preview
这是我的情景
[
{
"id": 1,
"legend": "businessModule",
"group": [
{
"id": 1,
"permission": {
"controleType": "ff",
"id": 2,
"key": "create Business"
},
"roles": [
{
"id": 1,
"name": "self"
},
{
"id": 2,
"name": "other"
}
]
},
{
"id": 1,
"permission": {
"controleType": "ff",
"id": 2,
"key": "edit business"
},
"roles": [
{
"id": 1,
"name": "self"
},
{
"id": 2,
"name": "other"
}
]
}
]
},
{
"id": 2,
"legend": "PanicModule",
"group": …Run Code Online (Sandbox Code Playgroud) angular2-forms angular2-template angular2-formbuilder angular
我做了一些研究,我很惊讶地发现它并不像应该的那样直截了当.
我知道有一些使用ngModel的方法.就像在typecript和Angular2等中绑定和获取下拉列表值一样.但我希望能够轻松地将我选择的选项绑定到我的formControlName var.
这是我尝试过的:
.HTML
<form id="myForm" name="father" [formGroup]="fatherForm" (ngSubmit)="createFather()">
<div class="row">
<select formControlName="pref" id="f">
<option value=null disabled selected>Prefijo</option>
<option *ngFor="let item of prefs" [ngValue]="hola">{{item.name}}</option>
</select>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
.TS
fatherForm: FormGroup;
this.fatherForm = this.formBuilder.group({
pref: ['AA']
});
this.prefs=[
{name: "AA"},
{name: "BB"}
];
Run Code Online (Sandbox Code Playgroud)
默认值有效.但是当我选择BB时,仍然会选择默认值.当默认值为''时会发生同样的情况
这种方法由Harry-ninh在FormBuilder Angular 2的Bind Select List中提出
我究竟做错了什么?
注意:当然,表单中还有其他输入,为简单起见,忽略它们.
编辑
我尝试在这个plunkr中使用完全相同的例子,它也不起作用. http://plnkr.co/edit/Rf9QSSEuCepsqpFc3isB?p=preview 发送表单后,表明尚未触及该值.

我正在尝试使用Reactive Forms Module在Angular 2中构建一个表单,并且我正在尝试以选择另一个字段所需的形式设置某些字段的验证.
我做错了什么吗?
ngOnInit() {
this.martialForm = this.fb.group({
'maritalStatus': [this.model.maritalStatus, [Validators.required]],
'spouseTitle': [this.spouseModel.title, null]
},{
validator: this.validateIsSpouse
})
}
validateIsSpouse(group: FormGroup) {
if(this.model.maritalStatus == "01"){
group.controls['spouseTitle'].setErrors({ isRequired: true });
}
return null;
}
Run Code Online (Sandbox Code Playgroud) 每当表单发生更改时,我都想取消选中一个复选框。该复选框是该表单的一部分,因此我只想取消选中该复选框以外的其他任何控件来更改值时。
我正在订阅这样的FormGroup的值更改
import { FormBuilder, FormGroup } from '@angular/forms';
export class App {
form : FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
firstName: 'Thomas',
lastName: 'Mann',
... many more fields ...
checkbox: true
})
this.form.valueChanges.subscribe(data => {
//if valueChange was not triggered by change in the checkbox
this.form.get('checkbox').setValue(false);
})
}
}
Run Code Online (Sandbox Code Playgroud)
我可以分别在每个其他控件中订阅valueChanges,但要避免这样做
我建立一个组件(html,css,spec.ts,ts在角)中,我总是希望endDate > startDate.我已经按照这个链接https://material.angular.io/components/datepicker/overview来制作多个日期选择器.
这是html我用于startDate和endDate的.
开始日期:
<div class="item item-1" fxFlex="50%" fxFlexOrder="1">
<mat-form-field>
<input matInput [matDatepicker]="picker1" placeholder="{{'PORTAL.STARTDATE' | translate}}" type="text" formControlName="startDate" [(ngModel)]="unavailability.startDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
</div>
Run Code Online (Sandbox Code Playgroud)
结束日期:
<div class="item item-2" fxFlex="50%" fxFlexOrder="2">
<mat-form-field>
<input matInput [matDatepicker]="picker2" placeholder="{{'PORTAL.ENDDATE' | translate}}" type="text" formControlName="endDate" [(ngModel)]="unavailability.endDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</div>
Run Code Online (Sandbox Code Playgroud)
validateForm()我用过的代码ts是:
validateForm() {
this.unavailabilityForm = this.formBuilder.group({
'startDate': [''],
'endDate': ['']
}); …Run Code Online (Sandbox Code Playgroud) validation datepicker angular-material angular2-forms angular2-formbuilder
注意到 angular5 表单的奇怪行为,使用构建器构建一个表单,其中包含捕获附加动态数据所需的表单数组,表单数组值仅在以下情况下更新:
this.formBuilder.array(this.getRow())Angular 版本 5.2.0 实验/示例代码在这里
第 1/2 点附录
更改似乎仅在未动态添加到 FormArray 的组件上注册
表单数组元素包含初始化过程的代码
ngOnInit(){
this.form = this.formBuilder.group({
name:[null],
description:[null],
hobbies:this.formBuilder.array([this.getRow()])
});
}
getRow():FormGroup{
return this.formBuilder.group({
hobby:[null],
description:[null]
});
}
Run Code Online (Sandbox Code Playgroud)
尽管很明显创建了额外的控件,但它们都是空的
然而,一旦触摸第一个元素(注意到从 Fishing 到 Fishing4 的变化,并且控制台输出现在具有剩余动态添加控件的值),所有新的动态字段值都会传播