我的嵌套表单目前以这种方式格式化:
ngOnInit() {
this.user = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
quest1: ['', Validators.required],
account: this.fb.group({
email: ['', Validators.required],
confirm: ['', Validators.required]
}),
questions: this.fb.group({
quest2: ['', Validators.required],
}),
});
}
Run Code Online (Sandbox Code Playgroud)
我通常会设置这样的值:
this.user.controls['quest1'].setValue('false');
但是因为formGroups是嵌套的,所以我不确定如何设置嵌套值.
如何设置"quest2"的值?在嵌套的formGroup中设置表单控件值的正确语法是什么?
编辑:我正在使用这种方式
this.user.controls['quest1'].setValue('false');
forms typescript angular2-forms angular angular-reactive-forms
我有两个数据数组:AssociatedPrincipals(以前保存的数据)和ReferencePrincipals(静态数据填充在下拉控件中).我很难从AssociatedPrincipals中获取先前的值,以便在页面加载时以动态数量(大多数示例使用单个下拉列表)显示/选择下拉列表.
我不确定如何设置表单(代码隐藏和HTML),特别是设置Select的formControlName.目前,每个下拉列表中的静态值都会填充,但我无法正确绑定所选值.
public ngOnInit() {
this.factsForm = this.formbuilder.group({
associatedPrincipals: this.formbuilder.array([]),
referencePrincipals: this.formbuilder.array([])
});
// Data for both of these methods comes from external source...
var responseData = // HTTP source...
// Push retrieved data into form
this.initPrincipals(responseData[0]);
// Push static data into form
this.initStaticData(responseData[1]);
}
public initPrincipals(principals?: IAssociatedPrincipal[]): FormArray {
principals.forEach((principal) => {
this.associatedPrincipals.push(this.createPrincipalFormGroup(principal));
});
}
public initStaticData(response: IReferencePrincipal[]) {
response.forEach((principal) => {
this.referencePrincipals.push(
this.formbuilder.control({
code: principal.code,
canHaveLead: principal.canHaveLead,
isDuplicate: false
}));
});
}
public createPrincipalFormGroup(principal: …Run Code Online (Sandbox Code Playgroud) 考虑以下演示https://stackblitz.com/edit/angular-pur1dt
无效时,我具有反应式表单控件,其中包含同步验证器和错误消息,显示在字段下方。
当控制失去重点时,将触发验证。控件下方是带有点击处理程序的按钮。问题是,当我单击按钮时,控件失去了焦点,发生了验证,显示了错误消息,并将按钮向下移动。据说这会阻止单击处理程序执行。有什么建议为什么会发生以及如何解决该问题?
我已经用评论更新了演示。注意:仅输入下方的按钮会重现该问题。首次单击后,标题将不会更新。
我希望能够使用组件构建一个响应式表单,而不是将其全部设置在单个父组件中。所以我创建了初始FormGroup并将其传递给组件,然后this.form.addControl(this.fb.group({ ... }));将它们的组添加到表单中。
例子
父组件
this.form = this.fb.group({}); // Empty
public ngAfterViewInit() {
// Throws error after trying to patchValue on the child component
this.form.get('example').patchValue({
field1: 'Hello World!'
});
}
Run Code Online (Sandbox Code Playgroud)
子组件
this.parentFormGroup.addControl(
'childGroup',
this.fb.group({
field1: [
'', [Validators.required]
],
etc...
}
);
Run Code Online (Sandbox Code Playgroud)
这一直有效,直到我尝试并this.form.get('childGroup').patchValue({ ... })在ngAfterViewInit父组件的生命周期挂钩中发出请求之后。它没有修补组,而是抛出:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has
changed after it was checked. Previous value: 'ng-valid: false'. Current value:
'ng-valid: true'.
Run Code Online (Sandbox Code Playgroud)
有没有办法让子组件将自己添加到 a FormGroup,而不是让父组件设置FormGroup控件和验证。我们需要在应用程序中以不同的方式和组合重用子组件,因此不想FormGroup在子组件之外不断重复声明,但这似乎不起作用。
angular angular-reactive-forms angular5 angular-changedetection
我需要使用 Validators.pattern 在响应式表单(表单控件)中提出验证模式。条件是字母数字,只允许使用下划线_、连字符-。不应允许任何类型的空间。是否有任何一种模式可以帮助我实现这一目标。
谢谢。
我有一个反应形式的组件:
@Component({
selector: 'app-new-user',
templateUrl: './new-user.component.html',
styleUrls: ['./new-user.component.css']
})
export class NewUserComponent implements OnInit {
registerForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.registerForm = this.formBuilder.group({
username: [null, [Validators.required]],
password: [null, [Validators.required]],
isActive: [null, [Validators.required]]
});
}
Run Code Online (Sandbox Code Playgroud)
使用这样的模板:
<form (ngSubmit)="onSubmit()" [formGroup]="registerForm" class="newUserForm">
<app-form-input
type="text"
formCtrlName="username">
</app-form-input>
<app-form-input
type="password"
formCtrlName="password">
</app-form-input>
<app-form-input
type="checkbox"
formCtrlName="isActive">
</app-form-input>
</form>
Run Code Online (Sandbox Code Playgroud)
如您所见,输入包裹在组件app-form-input中,如下所示:
@Component({
selector: 'app-form-input',
templateUrl: './form-input.component.html',
styleUrls: ['./form-input.component.css']
})
export class FormInputComponent implements OnInit {
@Input() type: string;
@Input() formCtrlName: string;
inputFormGroup: FormGroup;
constructor(private controlContainer: …Run Code Online (Sandbox Code Playgroud) 我试图建立一个Angular Reactive表单,其中一个帐户可以添加许多学生。
该表格似乎有效。当您点击添加学生时,它会创建一个新学生,但您会在控制台上看到提示
错误错误:找不到路径为'studentsArray-> 1-> firstName的控件
以此类推。
app.component.html
<form [formGroup]="accountForm">
<div>
<input formControlName="firstName" placeholder="First name">
</div>
<div>
<input formControlName="lastName" placeholder="Last name">
</div>
<div>
<input formControlName="phone" placeholder="Phone">
</div>
<div>
<input formControlName="email" placeholder="Email">
</div>
<button (click)="addStudent()" *ngIf="!showStudentForm">Add Student</button>
<div formArrayName="studentsArray">
<div *ngFor="let student of studentsArray.controls; let i = index" [formGroupName]="i">
<input formControlName="firstName" placeholder="First Name">
<input formControlName="lastName" placeholder="Last Name">
<input formControlName="dob" placeholder="Date of Birth">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
app.component.ts
import { Component, Input, OnChanges } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray, FormBuilder } …Run Code Online (Sandbox Code Playgroud) 基本上,我有一些表单输入,它们的验证相互依赖(即,如果您在一个时间范围内,“从”时间必须小于“到”时间),但我不确定如何去做这件事。
这是我的表单组:
this.form = this.fb.group({
fromTime: ["", [Validators.required, CustomValidator.myValidationFunction(this.form.get("toTime").value)]],
toTime: ["", [Validators.required]]
});
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我的验证器:
static myValidationFunction(testing) {
const toTime = testing; // only comes here 1 time
return control => {
return toTime /*this value never changes*/ ? null : { test: {} };
};
}
Run Code Online (Sandbox Code Playgroud)
但似乎值xortoTime仅在创建验证器时才第一次设置。有没有办法将动态输入传递给自定义验证器?
我对 angular 还很陌生,但已阅读有关自定义表单验证的文档,但似乎找不到我的答案
typescript angular angular-reactive-forms angular2-form-validation
我收到了一个传给formControl的@Input参数,该参数绑定到最大值应该为10的数字类型的输入。当用户键入更大的数字时,它不应更改输入值。
如何防止事件传播或获取旧值并重新设置?
我尝试了来自堆栈和github的许多其他解决方案,但是没有什么能解决我的问题。
valuecontrol: FormControl = new FormControl(0);
constructor(){
this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue=>{
if(newValue >= 10){
// set previous value
const oldValue = this.control.value;
console.log("old value = ", oldValue)
this.control.patchValue(oldValue);
}
})
}.
Run Code Online (Sandbox Code Playgroud)
演示:https : //stackblitz.com/edit/angular-6ocjfj? file = src/app/ app.component.ts
当我们单击父按钮时,我们想从父那里消耗子反应形式的数据。当前,我们正在使用viewchild来获取子cpomponent参考。我们正在获取所有静态数据,但未获取表单填写的数据...................................... ................................................... ......
parent.component.ts
@ViewChild(DetailsComponent) childrenComponent: childrenComponent;
save(){
let model=this.childrenComponent.buildDetailsModel();
/*here api to save model*/
}
children.component.ts
buildDetailsModel(): Details {
var a = {
reportedToId: this.detailsForm.get('reportedTo').value,
reportedOn: this.detailsForm.get('reportedTime').value,
identifiedById: this.detailsForm.get('identifiedBy').value,
identifiedOn: this.detailsForm.get('dateAndTimeIdentified').value,
locationTypeId: this.detailsForm.get('locationType').value,
addressId: this.detailsForm.get('locationAddress').value,
AddressLine: this.detailsForm.get('locationOfAddress').value,
description: this.detailsForm.get('description').value,
PeopleExposed: this.dataSource
};
return a;
}
parent.html
<child></child>
child.html
<form [formGroup]="detailsForm">
<div fxLayout="column wrap" fxLayoutGap="12px">
<div fxLayout="column" fxLayout.lt-sm="column" fxLayout.lt-md="column"
fxLayoutGap="24px">
<div fxFlex="row" fxLayoutGap="24px" fxLayout.lt-md="column">
<div fxFlex="column">
<mat-form-field>
<mat-label>Reported To</mat-label>
<mat-select matInput formControlName="reportedTo">
<mat-option value="Test 1">Test 1</mat-option>
<mat-option value="Test 2">Test 1</mat-option> …Run Code Online (Sandbox Code Playgroud) angular ×10
angular7 ×2
javascript ×2
typescript ×2
angular5 ×1
formarray ×1
formgroups ×1
forms ×1