我有一个有角度的2形式,其中我必须在某些条件下需要一个字段,如:
description: ['', Validators.required]
Run Code Online (Sandbox Code Playgroud)
仅在某些类型的条件下才需要此描述字段,例如:
if(true){descReq = true};
Run Code Online (Sandbox Code Playgroud)
我怎么能做到这一点,请建议.提前致谢!
有一个自定义的输入组件,它以反应形式用于验证:
@Component({
moduleId: module.id.toString(),
selector: 'custom-select',
templateUrl: 'custom-select.component.html',
styleUrls: ['custom-select.component.css']
})
export class CustomSelectComponent {
@Input() public items: SelectModel[];
public model: SelectModel;
constructor(private customSelectService: CustomSelectService) {
this.customSelectService.Selected.subscribe((data: SelectModel) => {
this.model = data;
});
}
public newSelect(select: SelectModel): void {
this.customSelectService.updateSelected(select);
}
}
Run Code Online (Sandbox Code Playgroud)
效果很好,我正在custom-select以反应形式使用,并希望按如下所示进行验证:
<custom-select id="country" [items]="selectItems" formControlName="country"></custom-select>
<div *ngIf=" myFrom.controls['country'].invalid && (myFrom.controls['country'].dirty
|| myFrom.controls['country'].touched) " class="ha-control-alert">
<div *ngIf="myFrom.controls['country'].hasError('required')">Country is required</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这就是我在组件中声明表格的方式
this.myFrom = this.formBuilder.group({
country: [null, Validators.required],
})
Run Code Online (Sandbox Code Playgroud)
但是当我添加formControlName验证时,会出现错误,提示名称为'country'的表单控件没有值访问器。我该如何处理?
angular-validation angular angular-reactive-forms angular-forms
我试图通过以下代码实现双向绑定:
export interface User {
name: string;
subscribed: boolean;
}
export class UserEditComponent implements OnInit {
modifiedUser: User;
userForm: FormGroup;
ngOnInit() {
this.userForm = this.fb.group({
name: ['', Validators.required],
subscribed: false
});
this.route.paramMap.switchMap((params: ParamMap) => {
return this.userService.getUser(params.get('id'));
}).subscribe((user) => {
this.modifiedUser = user;
this.userForm.setValue({
name: this.modifiedUser.name,
subscribed: this.modifiedUser.subscribed
});
});
this.userForm.valueChanges.subscribe((data) => {
this.modifiedUser.subscribed = data.subscribed;
});
}
}Run Code Online (Sandbox Code Playgroud)
<form [formGroup]="userForm">
<textarea class="form-control" formControlName="name">{{modifiedUser.name}}</textarea>
<input type="checkbox" class="custom-control-input" formControlName="subscribed">
</form>Run Code Online (Sandbox Code Playgroud)
但是,TypeError: Cannot assign to read only property 'subscribed' of object …
我有这样的形式:
<form id="save_form" (ngSubmit)="save()">
<input id="input_user" type="text" [formControl]="myForm" />
<button type="submit">save</button>
</form>
Run Code Online (Sandbox Code Playgroud)
我有这样的测试:
const inputUser: HTMLInputElement = fixture.nativeElement.querySelector("#input_user");
const saveForm: DebugElement = fixture.debugElement.query(By.css("#save_form"));
inputUser.value = "Bob";
//component.myForm.setValue("Bob");
saveForm.triggerEventHandler("ngSubmit", null);
fixture.detectChanges();
Run Code Online (Sandbox Code Playgroud)
在我的组件中,输入值未更新myForm。如果我使用注释掉的语法,则会更新表单,但不会填充输入标签。
我正在尝试模拟用户的输入值,是否应该通过测试中的输入值来更新formcontrol?我觉得如果我只是手动更新formcontrol,那我就不是在模拟用户。
更新:
//component.searchUsers.setValue("Bob");
const e: Event = document.createEvent("Event");
e.initEvent("input", false, false);
inputUser.value = "Bob";
inputUser.dispatchEvent(e);
fixture.detectChanges();
myForm.triggerEventHandler("ngSubmit", null);
fixture.detectChanges();
fixture.whenStable().then(() =>
expect(condition).toBe(true));
Run Code Online (Sandbox Code Playgroud) 假设我们有myFormGroup通过FormBuilder初始化的:
this.myFormGroup = this.fb.group(
{
field1: ['', SomeValidator1],
field2: ['', AnotherValidator2],
field3: [''],
...
}
);
Run Code Online (Sandbox Code Playgroud)
我知道我们可以禁用特定的表单控件,例如:
fb.control({value: 'my val', disabled: true});
Run Code Online (Sandbox Code Playgroud)
当然,我可以在示例中使用此语法,并将组中的每个控件标记为已禁用。但是表单组可能有很多控件。
因此,问题-是否有任何方法可以在通过FormBuilder 创建(而不是之后)禁用整个FormGroup / FormArray的同时?
ps我问这个问题的原因是因为我需要有条件地初始化具有不同类型用户权限的活动或禁用字段的表单组。
我在包装 mat-select 的自定义组件上使用 formControlName 时遇到很多问题。
现在看来我的自定义控件找不到表单组?即使自定义元素嵌套在 formGroup 下。
我有一个StackBlitz
但是当我将自定义组件嵌套在 formGroup 下时,问题就出现了,所有其他控件都可以找到 formGroup 但我的自定义组件似乎无法找到。
<form novalidate [formGroup]="tenantForm">
<label for="Id">Id</label>: <input class="form-control" formControlName="id" id="Id" name="Id" />
<custom-component-with-mat-select formControlName="culture" id="Culture" name="Culture"></custom-component-with-mat-select>
</form>
Run Code Online (Sandbox Code Playgroud)
在这个例子中,Id 字段可以正常工作,但是 Culture 字段抱怨没有嵌套在 FormGroup 中?
错误:formControlName 必须与父 formGroup 指令一起使用。您需要添加一个 formGroup 指令并将其传递给现有的 FormGroup 实例(您可以在类中创建一个)。
自定义组件应该如何与响应式表单和表单组一起使用?
我最初的问题是不记得导入 ReactiveFormsModule .. 也许我忘记再次导入某些东西?
这个答案是实现这一目标的设计方法吗?或者我错过了一个更简单的解决方案?
我需要实现一个控制值访问器吗??正如这里所解释的
只是对设计的方式感到困惑。
我的组件包装了 angular material 的 mat-select,如果我需要在 mat-select 上放置属性或让我的组件实现控制值访问器,我想我也很困惑?似乎没有任何效果。
angular-material angular angular-reactive-forms angular-forms
如何根据另一个字段的值有条件地验证一个字段?这是我尝试过的,但似乎不起作用
this.PDform = _formbuilder.group({
[...]
'intlNumber': ['',this.nationality == 'Abroad' ? Validators.compose([Validators.pattern(this.phoneNumberExp), Validators.maxLength(14), Validators.minLength(11), Validators.required]) : Validators ]
[...]
})
Run Code Online (Sandbox Code Playgroud) angular-validation angular angular-reactive-forms angular-forms angular5
我有一个角度反应形式,提交时我有这个代码:
(ngSubmit)="addVideo(); addVidForm.reset();"
Run Code Online (Sandbox Code Playgroud)
我正在标记我的主要表格 #addVidForm
我还有一些自定义验证器/控件,它们与我拥有的另一种表单相比很特别,在重置表单时不会发生这种情况。
我的验证器如下:
static mustBeVimeo(control: AbstractControl) : ValidationErrors | null {
if((control.value as string).startsWith("https://vimeo.com/")){ return null } else
if((control.value as string).startsWith("http://vimeo.com/")){ return null }
else { return { mustBeVimeo : true } }
}
Run Code Online (Sandbox Code Playgroud)
这是我在后端的表单:
this.addVideoForm = new FormGroup({
title: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
description: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(200)]),
category: new FormControl('', [Validators.required]),
link: new FormControl('', [Validators.required, AddVideoValidators.mustBeVimeo, Validators.maxLength(100)]),
visibleToGuests: new FormControl(this.visibleToGuests, [Validators.required])
})
Run Code Online (Sandbox Code Playgroud)
我还做了一个函数,它只是在后端重置表单并用一个按钮调用它,我得到了同样的错误。
不完全确定这整个事情的哪一部分失败了。该字段是正常输入,就像我在其他地方使用的一样。
我有一个输入组件customInput,它创建一个经典的输入字段并为其添加一些布局香料,没有额外的逻辑。
我想将一个 formControl 传递给它,将它绑定到它包含的输入。
应该这样使用:
<form [formGroup]="form">
<custom-input [formControl]="form.controls['control']"></custom-input>
</form>
Run Code Online (Sandbox Code Playgroud)
内部自定义输入:
export class HidInputFieldComponent {
@Input() formControl: AbstractControl
...
}
<div class="container">
<input [formControl]="formControl"/>
<label>label</label>
</div>
Run Code Online (Sandbox Code Playgroud)
现在当我初始化组件时,我得到
未指定名称的表单控件没有值访问器
在我的组件构造函数中记录控件,它是未定义的。
我做错了还是没有办法解决ControlValueAccessor?由于我实际上并没有构建自定义控件(我仍然使用经典输入),因此看起来很极端
我有这个例子:https : //stackblitz.com/edit/angular-asevei?file=app%2Fcdk-drag-drop-sorting-example.html
一切正常,但是在 将选择框“重置”到列表中的第一个值时。
有没有什么办法解决这一问题?它只是视觉上的,但对用户来说非常刺耳。我曾尝试使用该cdkDragPreview选项,但无法使其正常工作。
成分:
import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'cdk-drag-drop-sorting-example',
templateUrl: 'cdk-drag-drop-sorting-example.html',
styleUrls: ['cdk-drag-drop-sorting-example.css'],
})
export class CdkDragDropSortingExample {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
title: ['title'],
items: fb.array([
fb.group({
name: fb.control('1'),
note: fb.control('quux')
}),
fb.group({
name: fb.control('2'),
note: fb.control('bar')
}),
fb.group({
name: fb.control('3'),
note: fb.control('baz')
})
])
})
}
drop(event: …Run Code Online (Sandbox Code Playgroud)