我想在Ionic 2中的一个页面中使用FormBuilder.
首先,这是我的环境细节:在Windows 10上运行,并运行ionic --version给我2.0.0-beta.35
这是我的package.json文件的一部分:
...
"@angular/common": "2.0.0-rc.3",
"@angular/compiler": "2.0.0-rc.3",
"@angular/core": "2.0.0-rc.3",
"@angular/forms": "^0.3.0",
"@angular/http": "2.0.0-rc.3",
"@angular/platform-browser": "2.0.0-rc.3",
"@angular/platform-browser-dynamic": "2.0.0-rc.3",
"ionic-angular": "2.0.0-beta.10",
"ionic-native": "1.3.2",
"ionicons": "3.0.0"
...
Run Code Online (Sandbox Code Playgroud)
其次,这是涉及的两个主要文件:
insight.ts
import { Component } from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {
REACTIVE_FORM_DIRECTIVES,
FormBuilder,
FormControl,
FormGroup
} from '@angular/forms';
import { App, Insight } from '../../models';
import { InsightProvider } from '../../providers/insight/insight.service';
import { InsightImage, InsightLabel, InsightLink, InsightQuestion, InsightThought, InsightTodo, InsightVideo } from './shared'; …Run Code Online (Sandbox Code Playgroud) Angular 通过 FormBuilder 类引入了模型驱动表单,该类的主要方法group具有如下签名:
group(controlsConfig: {
[key: string]: any;
}): FormGroup;
Run Code Online (Sandbox Code Playgroud)
实际上是any一个格式如下的数组:
[
initial value of model's property,
sync validator(s),
async validator(s)
]
Run Code Online (Sandbox Code Playgroud)
仅需要第一个元素的地方。
我决定我想要比这更强类型的东西,特别是与强类型模型相关的任何东西,所以我根据 T 重新定义了该函数:
declare interface FormBuilder2 extends FormBuilder {
group<T>(controlsConfig: {
[K in keyof T]?: [T[K], ValidatorFn | ValidatorFn[] | null, ValidatorFn | ValidatorFn[] | null];
}): FormGroup;
}
Run Code Online (Sandbox Code Playgroud)
这也意味着 HTML 中的所有 formControlName(当然还有这里的 group() 调用)必须与模型的属性匹配,这是我更喜欢的。
这似乎可行,但有一个问题:
this.optionsForm = this.formBuilder2.group<CustomerModel>({
status: [this.model.status, [Validators.required], null],
lastOrder: [this.model.lastOrder, null, null],
comments: [this.model.comments, null, null],
}); …Run Code Online (Sandbox Code Playgroud) 我正在重置表格。它重置整个表单,但 FormArray 除外。
创建表单并在其中声明 formArray
createForm(){
this.invoiceForm = this.formBuilder.group({
'name': ['', Validators.required],
'gst': [''],
'currency': [''],
'addressLine1': ['', Validators.required],
'addressLine2': [''],
'city': ['', Validators.required],
'state': ['', Validators.required],
'country': ['', Validators.required],
'postalCode': ['', Validators.required],
'email': ['', [Validators.required, Validators.email]],
'invoiceparticulars': this.formBuilder.array([]),
'isGstshidden' : true
});
}
Run Code Online (Sandbox Code Playgroud)
尝试通过重置数据来修改传入数据中表单的详细信息,即使我调用了 reset() 函数 formArray 保留其中以前的条目。
modifyInvoice(index){
this.invoiceForm.reset();
let modifyData = this.modifyInvoiceArray[index];
console.log(modifyData);
this.invoiceNumber = modifyData.invoiceNumber;
this.invoiceForm.patchValue({name: modifyData.address.Name});
this.invoiceForm.patchValue({email: modifyData.email});
this.invoiceForm.patchValue({gst: modifyData.GSTnumber});
this.invoiceForm.patchValue({addressLine1: modifyData.address.AddressLine1});
this.invoiceForm.patchValue({addressLine2: modifyData.address.AddressLine2});
this.invoiceForm.patchValue({city: modifyData.address.City});
this.invoiceForm.patchValue({country: modifyData.address.Country});
this.invoiceForm.patchValue({postalCode: modifyData.address.PostalCode});
this.invoiceForm.patchValue({state: modifyData.address.State});
console.log(modifyData['particulars']);
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个表单生成器,从中生成一个特定的JSON格式体,将其放在服务器上,我遇到的问题是如何表示我的代码中指示的任务数组,这里是我的格式构建器:
this.form = fb.group({
Action: fb.group({
label: [],
actionType: [],
description: [],
HTTPMethod: [],
ressourcePattern: [],
status: [],
parameters: [],
linkedprocess: fb.group({
process: fb.group({
label: []
}),
/////////////////////
associatedTasks:[], // => here i want to represent the associated tasks
task: fb.group({ // it's an array of task
label:[]
})
/////////////////////
}),
labelParam: [],
descriptionParam: []
})
});
Run Code Online (Sandbox Code Playgroud)
这是我想从我的表单中获取的json格式:
{"Action": {
"label": "A7791",
"HTTPMethod": "POST",
"actionType": "indexation",
"status": "active",
"description": "descroption new",
"resourcePattern": "",
"creationDate": "30-05-2016 06:14:09",
"modificationDate": "13-06-2016 11:51:10",
"parameters": …Run Code Online (Sandbox Code Playgroud) 我正在使用Angular 2.0最终版本.
我想做的事?
- 我想只在输入接收焦点时显示一些通知(警告,输入要求).甚至更好,当他的父母(the div)有mouse hover事件.
从父(div)这样做很容易.Just(focus)= showNotifications()+ an ngIf - 完成工作.
但我想在show-notifications组件中封装此功能 - 并使其可重用..
鉴于我通过the control使用显示通知内部@Input()- 我可以做这两件事,如果我有权访问native HTML input element.你可以看到如何进入show-notifications.component.ts.这是代码:
app.component.html:
`<div>
<label>Name: </label>
<input formControlName="myName">
<show-notifications [the_control]="myName" ></show-notifications>
</div>`
Run Code Online (Sandbox Code Playgroud)
app.component.ts:
export class AppComponent {
myName = new FormControl("defaultvalue",[some validators..])
}
Run Code Online (Sandbox Code Playgroud)
显示-notifications.component.html:
<div class="show_requirements" *ngIf="hasfocus or parentDivHasMouseHover"> // incorect code and logic - i know, but you can see the idea..
<p *ngFor="let requirement of thisInputRequirements">{{requirement}}<p> …Run Code Online (Sandbox Code Playgroud) 所以我在这里使用了指南:https://angular.io/docs/ts/latest/cookbook/dynamic-form.html
我需要在现有字段中添加更多字段.我做了一些有用的东西,但它很笨重,当它击中它时它重置了形状.代码如下:
在dynamic-form.component.ts中:
add_textbox()
{
this.questions.push(this.questionService.create_textbox({key: "test", label: "Test"}));
console.log(this.questions);
this.form = this.qcs.toFormGroup(this.questions);
}
Run Code Online (Sandbox Code Playgroud)
在question.service.ts
create_textbox({key, value, label = '', order = 1, type = "text", description = "", help = ""}: {key?: any, value?: any, label?: any, order?: any, type?: any, description?: any, help?: any})
{
return new TextboxQuestion({
key,
label,
value,
order,
description,
type
});
}
Run Code Online (Sandbox Code Playgroud)
我的按钮也在,dynamic-form.component.html但我希望它可以dynamic-form-question.component.ts代替.这可能吗?
我正在尝试使用我从服务获得的值更新表单的值名称,一旦填充了位置字段.我通过观察表单对象的valueChanges来尝试这个.虽然价值不再改变,但它仍然可以连续发射.在debounceTime()和distinctUntilChanged()有没有影响:
bookmarkForm: FormGroup;
ngOnInit(): void {
this.bookmarkForm = this.formBuilder.group({
name: ['', Validators.required],
location: ['', Validators.required],
description:'',
shared: false
});
this.bookmarkForm.valueChanges
//.debounceTime(800)
//.distinctUntilChanged()
.subscribe(formData => {
if(formData.location){
console.log('location changed', formData);
this.bookmarkService.getBookmarkTitle(formData.location).subscribe(response => {
console.log('Response: ', response);
if(response){
this.bookmarkForm.patchValue({name:response.title}, {emitEvent: false});
}
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
html模板
<div class="container">
<div class="col-md-8 col-md-offset-2">
<form [formGroup]="bookmarkForm" novalidate (ngSubmit)="saveBookmark(bookmarkForm.value, bookmarkForm.valid)">
<div class="form-group">
<label for="location">Location*</label>
<input type="text" class="form-control" id="location"
required
name="location"
formControlName="location"
placeholder="Usually an URL">
<div …Run Code Online (Sandbox Code Playgroud) 我this.profile在javascript中的model()有一个名为的属性emails,它是一个数组{email, isDefault, status}
然后我将其定义如下
this.profileForm = this.formBuilder.group({
.... other properties here
emails: [this.profile.emails]
});
console.log(this.profile.emails); //is an array
console.log(this.profileForm.emails); // undefined
Run Code Online (Sandbox Code Playgroud)
在html文件中我用它作为
<div *ngFor="let emailInfo of profileForm.emails">
{{emailInfo.email}}
<button (click)="removeEmail(emailInfo)">
Remove
</button>
</div>
Run Code Online (Sandbox Code Playgroud)
如果我不添加它formGroup并将其用作数组 - 如下所示 - 它工作正常,但我有一个业务规则,该数组不应该为空,我无法根据此长度设置表单验证
emails : [];
this.profileForm = this.formBuilder.group({
.... other properties here
});
this.emails = this.profile.emails;
console.log(this.profile.emails); //is an array
console.log(this.emails); // is an array
Run Code Online (Sandbox Code Playgroud)
我尝试使用formBuilder.array但是那个是控件数组而不是数据数组.
emails: this.formBuilder.array([this.profile.emails])
Run Code Online (Sandbox Code Playgroud)
那么我的问题是如何将数组从模型绑定到UI以及如何验证数组的长度?
我有这个验证器:
export const PasswordsEqualValidator = (): ValidatorFn => {
return (group: FormGroup): Observable<{[key: string]: boolean}> => {
const passwordCtrl: FormControl = <FormControl>group.controls.password;
const passwordAgainCtrl: FormControl = <FormControl>group.controls.passwordAgain;
const valid = passwordCtrl.value.password === passwordAgainCtrl.value.passwordAgain;
return Observable.of(valid ? null : {
passwordsEqual: true
});
};
};
Run Code Online (Sandbox Code Playgroud)
以这种形式使用:
public signupForm: FormGroup = this.fb.group({
email: ['', Validators.required],
passwords: this.fb.group({
password: ['', Validators.required],
passwordAgain: ['', Validators.required]
}, {validator: CustomValidators.passwordsEqual()})
});
Run Code Online (Sandbox Code Playgroud)
使用它的模板的一部分:
<div formGroupName="passwords">
<div class="form-control" [ngClass]="{error: !signupForm.get('passwords').valid}">
<label class="label" for="password">Password</label>
<input class="input" id="password" formControlName="password" type="password"> …Run Code Online (Sandbox Code Playgroud) 我有一个业务单位列表,在注册表单上呈现为复选框以及文本框字段并进行验证.
<label for="inputFirstName" class="sr-only">First name</label>
<input type="text" formControlName="firstName" class="form-control" placeholder="First name">
<div class="checkbox" *ngFor="let bu of businessUnits">
<label><input type="checkbox" #instance value="{{bu.BuName}}" (click)="getCheckBoxValue(instance.checked, bu.BuName)">{{bu.BuName}}</label>
</div>
Run Code Online (Sandbox Code Playgroud)
从数据库表中检索业务单位列表,并在表单加载时呈现
businessUnits: BusinessUnit[] = [];
Run Code Online (Sandbox Code Playgroud)
在构造函数中,我正在验证这样的电子邮件
"firstName": new FormControl('', [Validators.required]),
Run Code Online (Sandbox Code Playgroud)
})
如何验证在页面加载时动态加载的checbox列表中至少有一个复选框?
谢谢
angular ×9
typescript ×3
forms ×1
generics ×1
interface ×1
ionic2 ×1
javascript ×1
json ×1
onfocus ×1
rxjs ×1