我正在使用ReactiveFormsModuleAngular2来创建包含表单的组件.这是我的代码:
foo.component.ts:
constructor(fb: FormBuilder) {
this.myForm = fb.group({
'fullname': ['', Validators.required],
'gender': []
});
}
Run Code Online (Sandbox Code Playgroud)
foo.component.html(with [formControl]):
<div class="fields">
<div class="field">
<label>Fullname*</label>
<input type="text" [formControl]="myForm.controls.fullname"/>
</div>
</div>
<div class="inline fields">
<label for="gender">Gender</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" checked="" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
<label>Male</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
<label>Female</label>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
foo.component.html(with formControlName):
<div class="fields">
<div class="field">
<label>Fullname*</label>
<input type="text" …Run Code Online (Sandbox Code Playgroud) radio-button form-control angular2-forms angular2-formbuilder angular
升级到RC5后,我们开始收到此错误:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});
Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
<input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
</div>
Run Code Online (Sandbox Code Playgroud)
看起来在RC5中两者不能再一起使用,但我找不到替代解决方案.
以下是产生异常的组件:
<select class="field form-control" [formGroup]="form" [(ngModel)]="cause.id" [name]="name">
<option *ngFor="let c of causes" [value]="c.text">{{c.text}}</option>
</select>
Run Code Online (Sandbox Code Playgroud) 我无法找到如何将所有表单的字段标记为触摸.主要问题是,如果我不触摸字段并尝试提交表单 - 验证错误未显示.我的控制器中有一段代码占位符.
我的想法很简单:
如果有人知道如何在提交时显示错误,而不实施新方法 - 请分享.谢谢!
我的简化形式:
<form class="form-horizontal" [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
<input type="text" id="title" class="form-control" formControlName="title">
<span class="help-block" *ngIf="formErrors.title">{{ formErrors.title }}</span>
<button>Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
而我的控制器:
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
@Component({
selector : 'pastebin-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent implements OnInit {
form: FormGroup;
formErrors = {
'title': ''
};
validationMessages = {
'title': {
'required': 'Title is required.'
}
};
constructor(private fb: FormBuilder) {
}
ngOnInit(): …Run Code Online (Sandbox Code Playgroud) 使用Angular 2,双向绑定在模板驱动的表单中很容易 - 您只需使用香蕉盒语法.您将如何以模型驱动的形式复制此行为?
例如,这是标准的反应形式.让我们假装它看起来比它看起来复杂得多,有很多种不同的输入和业务逻辑,因此比模板驱动的方法更适合模型驱动的方法.
export class ExampleModel {
public name: string;
// ... lots of other inputs
}
@Component({
template: `
<form [formGroup]="form">
<input type="text" formControlName="name">
... lots of other inputs
</form>
<h4>Example values: {{example | json}}</h4>
`
})
export class ExampleComponent {
public form: FormGroup;
public example: ExampleModel = new ExampleModel();
constructor(private _fb: FormBuilder) {
this.form = this._fb.group({
name: [ this.example.name, Validators.required ]
// lots of other inputs
});
}
this.form.valueChanges.subscribe({
form => {
console.info('form values', form);
} …Run Code Online (Sandbox Code Playgroud) 我在Plunkr上有一个Angular 2 RC4基本表单示例,似乎抛出以下错误(在Chrome DEV控制台中)
这是傻瓜
https://plnkr.co/edit/GtPDxw?p=preview
错误:
browser_adapter.ts:82 EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./App class App - inline template:1:7
ORIGINAL EXCEPTION: formGroup expects a FormGroup instance. Please pass one in.
Example: <form [formGroup]="myFormGroup">
ORIGINAL STACKTRACE:
Error: formGroup expects a FormGroup instance. Please pass one in.
Example: <form [formGroup]="myFormGroup">
at new BaseException (https://npmcdn.com/@angular/forms@0.2.0/src/facade/exceptions.js:27:23)
at FormGroupDirective._checkFormPresent (https://npmcdn.com/@angular/forms@0.2.0/src/directives/reactive_directives/form_group_directive.js:110:19)
at FormGroupDirective.ngOnChanges (https://npmcdn.com/@angular/forms@0.2.0/src/directives/reactive_directives/form_group_directive.js:39:14)
at DebugAppView._View_App0.detectChangesInter
Run Code Online (Sandbox Code Playgroud) 我'question1'在表单对象中有一个名称的表单控件,parentForm我已按以下方式订阅它.
它有两个选项的单选按钮Yes和No,当我选择No,我得到Yes,当我选择Yes它的一个No.
this.parentForm.controls['question1'].valueChanges.subscribe(
(selectedValue) => {
// If option `No is selected`
console.log(selectedValue); // displays No. OK
console.log(this.parentForm.value['question1']); // displays Yes. Problem is here
}
);
Run Code Online (Sandbox Code Playgroud)
selectedValue变量具有正确的值,但如果我这样做,console.log(this.parentForm.value['question1']则给出前一个值.
我试图setTimeout()在检索之前输入一个值this.parentForm.value['question1'],它只是工作正常.
setTimeout(() => {
console.log(this.parentForm.value['question1']); // gives the correct value.
}, 500);
Run Code Online (Sandbox Code Playgroud)
但我的问题是,为什么parentForm在控件的值发生变化时不会更新,而且我只是在更改值后才检索其值.
注意:我不想观察parentForm.valueChanges,而不是我的要求.
我将我的项目迁移到 angular 11,我注意到我添加的全局验证FormBuilder.group不推荐使用以下消息:
group is deprecated: This api is not typesafe and can result in issues with Closure Compiler renaming.
Use the `FormBuilder#group` overload with `AbstractControlOptions` instead.
Run Code Online (Sandbox Code Playgroud)
所以这已被弃用:
ingredientForm = this.fb.group({
ingredientType: ['', Validators.required],
ingredientFlavor: [''],
isMultiFlavor: [''],
ingredientBrand: [''],
ingredientName: [''],
imageFile: ['']
}, {validators: [ValidateThirdNumber.validate]});
Run Code Online (Sandbox Code Playgroud)
如果没有这个validators选项,它就不是。
我的ValidateThirdNumber验证器:
class ValidateThirdNumber {
static validate(control: AbstractControl): void {
if (control) {
const isMultiFlavor = control.get('isMultiFlavor')?.value;
const ingredientFlavor = control.get('ingredientFlavor')?.value;
const ingredientBrand = control.get('ingredientBrand')?.value;
const ingredientName …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用disabled我的模型驱动形式.我有以下表格:
this.form = this.formBuilder.group({
val1: ['', Validators.required],
val2: [{value:'', disabled:this.form.controls.val1.valid}]
});
Run Code Online (Sandbox Code Playgroud)
我发现了一个错误(没有找到controls的this.form可能是因为我使用)this.form内this.form.
我该如何解决这个问题?
PS我也尝试[disabled]='...'在我的html里面添加,但是我得到一个警告,说我应该使用formBuilder
我form在Angular中创建了以下内容FormBuilder:
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
'name': ['', [Validators.required],
'surname': ['', [Validators.required],
'email': ['', [validateEmail]],
'address': fb.group({
'street': [''],
'housenumber': [''],
'postcode': ['']
}, { validator: fullAddressValidator })
});
}
Run Code Online (Sandbox Code Playgroud)
是否存在以编程方式附加新字段(如FormControlnew或new)的FormGroup方法myForm?
我的意思是,如果我想按需或在某些条件下添加新字段,如何将项目添加到第一次创建的同一表单中constructor?
我有一个字段,我想用多个验证器验证.
使用Module Driven方法,代码看起来像这样:
this.exampleForm = this.fb.group({
date_start : ['', Validators.compose([
Validators.required,
Validators.pattern("[0-9]{2}-[0-9]{2}-[0-9]{4}")
])
]
})
Run Code Online (Sandbox Code Playgroud)
但是我也可以在没有Validators.compose()的情况下编写这个:
this.exampleForm = this.fb.group({
date_start : ['', [
Validators.required,
Validators.pattern("[0-9]{2}-[0-9]{2}-[0-9]{4}")
]
]
})
Run Code Online (Sandbox Code Playgroud)
它工作得很好.我个人比较喜欢第二个版本(无撰写),更少的代码和更好的可读性.这就引出了一个问题,我为什么要使用Validators.compose()?