我的嵌套表单目前以这种方式格式化:
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) 我有一个FormGroup,嵌套在另一个FormGroup中,我想在其中使用get()获得某个控件。
我尝试了以下解决方案,该解决方案不起作用:
formGroup.get('formGroupKey').get('formControlKey');
Run Code Online (Sandbox Code Playgroud)
但这会引发错误。第一个get()有效(并正确返回FormGroup),但是第二个get引发异常(path.split不是函数)
知道我该如何解决吗?
@更新
我现在用这种方式解决了(尽管这不是一个很好的解决方案):
formGroup.get(tab.id)['controls'][segment.id];
Run Code Online (Sandbox Code Playgroud) 考虑以下演示https://stackblitz.com/edit/angular-pur1dt
无效时,我具有反应式表单控件,其中包含同步验证器和错误消息,显示在字段下方。
当控制失去重点时,将触发验证。控件下方是带有点击处理程序的按钮。问题是,当我单击按钮时,控件失去了焦点,发生了验证,显示了错误消息,并将按钮向下移动。据说这会阻止单击处理程序执行。有什么建议为什么会发生以及如何解决该问题?
我已经用评论更新了演示。注意:仅输入下方的按钮会重现该问题。首次单击后,标题将不会更新。
我有一个反应形式的组件:
@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) 我有一个确认密码formcontrol,我想验证.
当密码与确认密码输入中的值不同时,我想显示我的mat-error元素.为此我有一个叫做的函数equalPasswords().如果函数是相同的,那么我们收到true,如果没有,我们收到false.
<mat-form-field>
<input matInput placeholder="Repeat password" [formControl]="password2" type="password">
<mat-error *ngIf="password2.invalid && password2.hasError('required')">Password is required</mat-error>
<mat-error *ngIf="!equalPasswords() && !password2.hasError('required')">Passwords need to match</mat-error>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
我检查了控制台,当我在密码框中输入两个不同的输入时,equalPasswords()返回false.但是它仍然没有显示DOM中的错误.
有人知道如何解决这个问题吗?
Signup.component.ts
@Component({
selector: 'app-sign-up',
templateUrl: 'sign-up.component.html',
styleUrls: ['sign-up.component.css']
})
export class SignUpComponent implements OnInit {
mySignupForm: FormGroup;
countries = countries;
uniqueUsernameMessage;
uniqueEmailMessage;
formSubmitted = false;
@Output() closeSubmenu = new EventEmitter();
@ViewChild('select') select;
constructor(
private authService: AuthenticationService,
private route: Router,
private navigationService: NavigationService){}
get firstName() { return this.mySignupForm.get('firstName'); }
get lastName() { return this.mySignupForm.get('lastName'); …Run Code Online (Sandbox Code Playgroud) 我收到了一个传给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
在Angular,有一个方法来识别FormGroup/ FormControl在一个动态FormArray发射的valueChanges事件?
我FormArray是动态的。它开始是空的和用户可以添加FormGroup到FormArray通过点击一个按钮。
当valueChanges时,我需要重新验证控件。由于我不知道哪个控件发出了该事件,因此我将遍历整个控件FormArray并验证所有FormGroup(FormControl即使仅更改了一个控件),这是每次数组中的任何内容发生更改时。我如何避免这样做?
this.myFormArray
.valueChanges
.subscribe(data => this.onValueChanged(data));
onValueChanged(data?: any): void {
// the data I receive is an entire form array.
// how can I tell which particular item emitted the event,
// so I don’t need to loop through entire array and run validation for all items.
for (let control in this.myFormArray.controls) {
// run …Run Code Online (Sandbox Code Playgroud) 当我们单击父按钮时,我们想从父那里消耗子反应形式的数据。当前,我们正在使用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
formarray ×1
formgroups ×1
forms ×1
rxjs ×1
typescript ×1