如果我在没有输入任何内容的情况下通过文本输入进行选项卡,则错误消息msg显示指示所需的验证器已正确触发.但是,如果我在其中一个字段中键入任何内容,控制台会立即抛出此错误:
Cannot read property 'required' of null
Run Code Online (Sandbox Code Playgroud)
这是我的组件:
import { PasswordValidators } from './../validators/password.validators';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-changepassword-form',
templateUrl: './changepassword-form.component.html',
styleUrls: ['./changepassword-form.component.css']
})
export class ChangepasswordFormComponent {
form;
constructor(fb: FormBuilder) {
this.form = fb.group({
newPassword: ['', Validators.required],
confirmPassword: ['', Validators.required]
})
}
get newPassword() {
return this.form.get('newPassword');
}
get confirmPassword() {
return this.form.get('confirmPassword');
}
}
Run Code Online (Sandbox Code Playgroud)
和HTML:
<form [formGroup]="form">
<div class="form-group">
<label for="newPassword">New Password</label>
<input formControlName="newPassword" …Run Code Online (Sandbox Code Playgroud) 前言:
我正在努力弄清楚听起来像是嵌套角形的简单过程.我在这里处理一些组件和一些formGroups与formArrays被动态创建和它扔我.
为大型代码转储道歉,但它是我能够想出来试图解释我的问题的最小例子.
父组件非常直接,因为它只有两个formControls.然后我将表单传递给tasks组件以访问它.
this.intakeForm = this.fb.group({
requestor: ['', Validators.required],
requestJustification: ['', Validators.required]
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<form [formGroup]=“intakeForm”>
<app-tasks
[uiOptions]="uiOptions"
[intakeForm]="intakeForm">
</app-tasks>
</form>
Run Code Online (Sandbox Code Playgroud)
这里的一些方法将触发generateTask创建新表单组的方法.
ngOnInit() {
this.intakeForm.addControl('tasks', new FormArray([]));
}
// Push a new form group to our tasks array
generateTask(user, tool) {
const control = <FormArray>this.intakeForm.controls['tasks'];
control.push(this.newTaskControl(user, tool))
}
// Return a form group
newTaskControl(user, tool) {
return this.fb.group({
User: user,
Tool: tool,
Roles: this.fb.array([])
})
}
Run Code Online (Sandbox Code Playgroud)
HTML: …
我有一个广播组,每个选项使用相同的表单控件.是否可以仅禁用红色单选按钮?我知道您可以在颜色 表单控件上设置禁用标志,但这将禁用所有单选按钮.
<fieldset [formGroup]="colorForm">
<legend>
Choose color
</legend>
<div class="radio">
<label>
<input type="radio" value="red" formControlName="color">
Red
</label>
</div>
<div class="radio">
<label>
<input type="radio" value="green" formControlName="color">
Green
</label>
</div>
<div class="radio">
<label>
<input type="radio" value="blue" formControlName="color">
Blue
</label>
</div>
Run Code Online (Sandbox Code Playgroud) 正如标题所说,我有一个包含多个<mat-select>内容的反应形式.在初始表单加载时,即使form.value显示初始选项,也不会显示初始选项.
相关组件:
export class DesJobInfoEditComponent implements OnInit {
...
currentJobData: IJob;
jobTypes: IJobType[];
...
constructor(private fb: FormBuilder) {
...
// Construct forms
this.createForm();
this.initializeForm();
}
createForm() {
this.editJobInfoForm = this.fb.group({
...
JobType: '', // mat-select
...
});
}
initializeForm() {
this.rebuildForm();
}
rebuildForm() {
this.editJobInfoForm.reset({
...
JobType: this.jobTypes[this.currentJobData.JobType].DisplayDesc,
...
});
}
Run Code Online (Sandbox Code Playgroud)
}
相关的HTML:
<mat-form-field fxFlex>
<mat-label>Job Type</mat-label>
<mat-select formControlName="JobType" placeholder="Job Type">
<mat-option *ngFor="let jobType of jobTypes" value="jobType.value">
{{ jobType.DisplayDesc }}
</mat-option>
</mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
加载表单时,选择不显示最初选择的选项,但是,它们设置正确,显然:
Form value …Run Code Online (Sandbox Code Playgroud) 请协助,我想删除表格中的所有验证人,请告知是否可能,如果您有表格组20或更多表单控件,如果不是更好的方法删除验证器,请参阅下面的示例.
ngOnInit() {
this.exampleFormGroup = this.formBuilder.group({
surname: ['', [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]],
initials: ['', [Validators.required, Validators.maxLength(4)]]
});
}
public removeValidators() {
this.exampleFormGroup.get('surname').clearValidators();
this.exampleFormGroup.get('initials').clearValidators();
this.exampleFormGroup.updateValueAndValidity();
}
public addValidators() {
this.exampleFormGroup .get('surname').setValidators([Validators.required,Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]);
this.exampleFormGroup.get('initials').setValidators([Validators.required, Validators.maxLength(4)]);
this.exampleFormGroup.updateValueAndValidity();
}
Run Code Online (Sandbox Code Playgroud)
上面的方法addValidators()将添加验证器,并removeValidators()在执行时删除验证器.但我遇到的问题是,我必须指定表单控件我试图清除验证器.有没有办法this.exampleFormGroup.clearValidators();在表单中完成并清除所有内容并再次this.exampleFormGroup.setValidators()将其设置回来.我知道我可能会要求一个独角兽,但在formGroup有20个或更多控件的情况下,清除和设置验证器可能会很痛苦,因此非常感谢如何处理这些场景的地图.
我有一个更改函数,该函数将传递给反应形式控件的更改事件的更改事件,该控件评估脏状态并检查控件上是否有任何错误,如果是,则将布尔标志设置为true / false。然后,此布尔标志用于确定是否显示<div>具有错误消息的元素。这在浏览器中可以正常工作,但是在运行单元测试时,永远不会将“ dirty”设置为true。这是我的代码:
的HTML
<form [formGroup]="myForm" novalidate>
<input id="age" formControlName="age" (change)="onChange()" />
<div id="ageError" *ngIf="ageIsError()">
<label>Age has errored</label>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
零件
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
age: [null, [Validators.min(18)]]
});
}
onChange() {
if (this.ageIsError())
// do something
}
ageIsError() {
return this.myForm.controls.age.hasError('min') &&
this.myForm.controls.age.dirty;
}
Run Code Online (Sandbox Code Playgroud)
单元测试
it('should show error message when age is less than 18', fakeAsync(() => {
let age = component.myForm.controls.age;
age.setValue('10', { emitEvent: …Run Code Online (Sandbox Code Playgroud) unit-testing jasmine typescript angular angular-reactive-forms
我在尝试实现嵌套的角度 FormGroup 时遇到了问题。
我正在使用描述表单输入的特定方案(客户端和服务器之间的接口)。我想创建一个具有某些验证的 FormGroup,并找到使用方案对象初始化 FormGroup 的最简单有效的方法。
方案对象属性本身就是对象,因此我想为其中的每一个创建自己的 FormGroup。此外,包含主 FormGroup 的组件包含应该连接到内部 FromGroups(方案对象的键)的子组件。
例如:
MySchema: {
velocity:
{
speed: number,
direction: number
},
position:
{
x: number,
y: number
}
}
Run Code Online (Sandbox Code Playgroud)
主窗体应该有 2 个内部组件 - 速度组件和位置组件。
每个子组件都应该连接到一个子表单组(速度组件到速度组等等)并显示相关的验证。
主窗体应连接到主 FormGroup。
这是一个小例子,在我们的项目中,架构要大得多,手动编写所有内部元素似乎是错误的。
我希望你能帮助我找到更好的方法。
谢谢。
更新
也许我的问题不够清楚..有没有办法将大对象转换为角度形式组/形式控件?
我的每个表单都包含我从服务器收到的对象,手动在 fb 中编写每个元素似乎是错误的。
再次感谢所有已经回答的人
我正在使用带有 mat 自动完成功能的反应式表单。我在应用程序的其他部分使用了自动完成功能,但我无法弄清楚。我有一个formarray,每次我想在我的情况下添加一个新传感器时都会添加一个输入。自动完成在我的第一个输入中工作正常,但是当我尝试添加更多输入时显示错误:错误:必须在索引处为表单控件提供一个值:1
HTML:
<div class="row">
<div class="input-field col s10">
<div class="form-group">
<div formArrayName="sensors_id">
<div *ngFor="let sensor of addHomeboxPForm.get('sensors_id')['controls']; let i = index">
<br>
<input formControlName="{{i}}" type="text" placeholder="Select Sensor" aria-label="Number" matInput [matAutocomplete]="auto1">
<mat-autocomplete autoActiveFirstOption #auto1="matAutocomplete" [displayWith]="displayWith" >
<mat-option (onSelectionChange)="updateForm($event, [sensor.sensors_id], 'sensors_id')" *ngFor="let sensor of filteredOptionsS | async" [value]="sensor.sensor_serial">
{{sensor.sensor_serial}}
</mat-option>
</mat-autocomplete>
<div class="button-left">
<button *ngIf="addHomeboxPForm.controls.sensors_id.value.length > 1" type="button" class="fa" (click)="onRemoveItem(i)">RemoveSensor</button>
</div>
</div>
</div>
</div>
<div class="input-field col s2">
<button type="button" class="btn" (click)="onAddItem()">AddSensor</button>
</div>
Run Code Online (Sandbox Code Playgroud)
TS:
格式数组: 'sensors_id': this.fb.array([], Validators.required),
updateForm(ev: …Run Code Online (Sandbox Code Playgroud) 我通过注入 NgControl 编写了一个反应式组件,并使用 @Self 装饰器进行装饰。我的问题与此类组件的单元测试有关。请看下面的代码:
免责声明:我已经快速复制了代码并进行了一些内联更改。因此,这可能不是编译器满意的代码。
我的反应组件:
@Component({
selector: 'text-input',
templateUrl: '<input type="text" class="native_input" />'
})
class TextInput implements ControlValueAccessor {
protected constructor(@Self() public controlDir: NgControl) {
this.controlDir.valueAccessor = this;
}
// ...followed by other ControlValueAccessor methods
}
Run Code Online (Sandbox Code Playgroud)
单元测试:
describe('TextInput -', () => {
let fixture: ComponentFixture<TextInputHost>;
let textInput: TextInput;
let inputElement: HTMLInputElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TextInput, TextInputHost
],
imports: [
FormsModule, ReactiveFormsModule
]
});
}));
beforeEach(fakeAsync(() => {
fixture = getTestBed().createComponent(TextInputHost);
textInput = fixture.componentInstance.textInputComponent;
textInput.writeValue('TestValue');
inputElement …Run Code Online (Sandbox Code Playgroud) unit-testing angular-components angular angular-reactive-forms
我有一个反应式表单,当用户在输入中按下 ESC 键时,我想在表单隐藏之前显示一个“你确定”模式。
一旦显示模态,我就会在控制台中收到以下异常:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has
changed after it was checked. Previous value: 'ng-untouched: true'. Current
value: 'ng-untouched: false'.
Run Code Online (Sandbox Code Playgroud)
这是一个显示问题的 stackblitz(焦点输入并按 ESC)
注意:当您聚焦输入,模糊并再次聚焦时,问题不会再次出现ng-untouched变化。
有什么解决方法吗?实现此类功能的推荐方法是什么?
提前致谢!
angular ×10
typescript ×3
javascript ×2
unit-testing ×2
formarray ×1
jasmine ×1
ng-bootstrap ×1