我有一个来自 control 的自定义选择器app-date-picker。它实现了ControlValueAccessor. 我有一个名为的组件MyPage,其中包含此自定义表单控件:
<app-date-picker class="address__from-date" [(ngModel)]="fromDate"></app-date-picker>
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一个单元测试来MyPage测试绑定的两个方向。我已经对其他表单字段执行了此操作,效果很好,例如:
it('should bind zip code', fakeAsync(() => {
const formControl = element.query(By.css('.address__zip-code input')).nativeElement;
// model -> view
component.zipCode = 76777;
fixture.detectChanges();
tick();
expect(formControl.value).toEqual('76777');
// view -> model
formControl.value = '89556';
formControl.dispatchEvent(new Event('input'));
expect(component.zipCode).toEqual(89556);
}));
Run Code Online (Sandbox Code Playgroud)
当我尝试为自定义表单控件执行此操作时,出现了问题。到目前为止,我只能测试一个绑定方向,即使如此,它也需要使用ng-reflect-model,这太糟糕了:
it('should bind from-date', fakeAsync(() => {
const formControl = element.query(By.css('.address__from-date app-date-picker')).nativeElement;
// model -> view
component.fromDate = '01/2017';
fixture.detectChanges();
tick();
expect(formControl.attributes['ng-reflect-model'].value).toEqual('01/2017');
// view -> model
// Not sure …Run Code Online (Sandbox Code Playgroud) unit-testing angular2-forms angular2-testing angular angular-forms
我正在尝试对“passwordConfirm”字段进行验证,但出现一个奇怪的错误:ERROR TypeError: Cannot read property 'get' of undefined
这是我的代码:
loginForm: FormGroup;
ngOnInit(){
this.loginForm = new FormGroup({
'email': new FormControl(null, [Validators.required, Validators.email]),
'password': new FormControl(null, Validators.required),
'passwordConfirm': new FormControl(null, [Validators.required, this.checkIfMatchingPasswords.bind(this)]),
});
}
checkIfMatchingPasswords() {
return this.loginForm.get('password').value === this.loginForm.get('passwordConfirm').value ? null : { notSame: true} // error
}
Run Code Online (Sandbox Code Playgroud) 我正在使用 TypeScript 学习 Angular 5。我对此完全陌生。我现在正在尝试构建一个表单并验证它。但它无法正常工作。
这是我的组件:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
animations: [routerTransition()]
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
errors = [];
constructor(private fb: FormBuilder, public router: Router, private globals: GlobalsService, private http: Http) {
}
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl("", Validators.required),
password: new FormControl("")
});
}
onLoggedin(formData) {
alert("Submit form");
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我在电子邮件字段上设置“必需”验证属性。这是我的html。
<div class="login-page" [@routerTransition]>
<div class="row justify-content-md-center">
<div class="col-md-4">
<img src="assets/images/logo.png" width="150px" class="user-avatar" />
<h1>Yo Cash Flow</h1>
<div …Run Code Online (Sandbox Code Playgroud) 在构造函数中添加表单构建器时。我一直收到错误。我已经在 app.module 中添加了 ReactiveFormsModule 。
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'app',
template: require('./app.component.pug'),
styles: [require('./app.component.scss')]
})
export class AppComponent {
private loginForm: FormGroup;
constructor(private fb: FormBuilder) {}
}
Run Code Online (Sandbox Code Playgroud)
示例 app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)
这是错误:
我需要验证用户创建表单。我必须针对 2 种情况验证电子邮件:
这是必需的
用户只能收到来自特定域的电子邮件(例如仅来自 gmail)。
对于第一个场景,我需要验证“更改”,对于“模糊”事件的第二个场景。问题是,我无法为不同的事件验证相同的字段。至少我不知道该怎么做。我需要这样的东西:
this.userForm = this.formBuilder.group({
email: new FormControl("", {validators: Validators.required, updateOn: "change"}),
email: new FormControl("", {validators: validateEmail, updateOn: "blur"}),
... // more fields
});
Run Code Online (Sandbox Code Playgroud)
知道如何实现这一目标吗?
我有一个自定义复选框组件,它当前使用一些 Material Icons 图标来显示。我在几个地方使用了这个组件,但是我遇到了一个特定实例的问题。
我在左侧有一个带有复选框的网格,可以一次选择多行。当<i>用于从字体显示图标时,这些复选框可以正常工作。当我改用 SVG 时,这些复选框会中断。我一次只能选择一个,我不能取消选择一个已选择的。如果我选中一个框,它会像您期望的那样检查。如果我再次单击它,则什么也没有发生——该框保持选中状态。如果我选中一个不同的框,第一个是未选中的。
这是原始的复选框组件模板:
<label class="my-checkbox" [class.pointer]="!disabled">
<input
type="checkbox"
class="form-control norowclick"
[class.indeterminateinput]="indeterminate"
[checked]="checked"
[(ngModel)]="value"
(blur)="onBlur()"
[disabled]="disabled"
>
<i class="material-icons md-18 indeterminate norowclick">indeterminate_check_box</i>
<i class="material-icons md-18 checked norowclick">check_box</i>
<i class="material-icons md-18 unchecked norowclick">check_box_outline_blank</i>
</label>
Run Code Online (Sandbox Code Playgroud)
这是新模板,使用angular-svg-icon. 在呈现时,有一个<svg-icon>与元素<svg>元素作为其唯一的孩子。这是对任何代码所做的唯一更改,这就是导致它中断的原因。
<label class="my-checkbox" [class.pointer]="!disabled">
<input
type="checkbox"
class="form-control norowclick"
[class.indeterminateinput]="indeterminate"
[checked]="checked"
[(ngModel)]="value"
(blur)="onBlur()"
[disabled]="disabled"
>
<svg-icon name="indeterminate_check_box" class="icon-18 indeterminate norowclick"></svg-icon>
<svg-icon name="check_box" class="icon-18 checked norowclick"></svg-icon>
<svg-icon name="check_box_outline_blank" class="icon-18 unchecked norowclick"></svg-icon>
</label>
Run Code Online (Sandbox Code Playgroud)
这是复选框组件代码:
@Component({
selector: …Run Code Online (Sandbox Code Playgroud) 我正在使用 angular 7 应用程序,并且正在编写一个通用的动态表单创建器。我正在使用反应式表单并ng-template and <ng-container *ngTemplateOutlet>递归显示表单元素。项目的代码可以在这里看到。
但我面临以下错误
ERROR Error: Cannot find control with name: 'data'
at _throwError (forms.js:1775)
at setUpControl (forms.js:1683)
at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:4532)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:5030)
at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:4980)
at checkAndUpdateDirectiveInline (core.js:9239)
at checkAndUpdateNodeInline (core.js:10507)
at checkAndUpdateNode (core.js:10469)
at debugCheckAndUpdateNode (core.js:11102)
at debugCheckDirectivesFn (core.js:11062)
Run Code Online (Sandbox Code Playgroud)
但是如果我看到我的 formGroup 对象,我可以看到一个带有数据的控件作为控件的名称,如下所示。
我在做什么错误?请帮忙。
问题的重现是Here stackblitz
angular angular-reactive-forms angular-forms angular6 angular7
如何formcontrol(option)动态添加formarray? 我想动态地将问题添加到formarray. 单击按钮后,它应该更新显示。我正在使用角度 7。
ngOnInit() {
this.quizForm = this.fb.group({
questions: this.fb.array([]),
questions2: this.fb.array([]),
});
}
//creating formcontrol
createItem(): FormGroup {
return this.fb.group({
ques: '',
});
}
//pushing code
genField() {
this.message = true;
this.questions = this.quizForm.get('questions') as FormArray;
this.questions.push(this.createItem());
}
Run Code Online (Sandbox Code Playgroud)
我想在按钮单击时动态添加表单控件选项,并且表单控件应该在formArrayName="questions".
<form [formGroup]="quizForm" class="adjust-form">
<div formArrayName="questions"
*ngFor="let item of quizForm.get('questions').controls; let i = index;">
<div class="col-md-10 col-sm-6 mt-3 mb-3" [formGroupName]="i">
<label>{{i +1}} - {{question}} </label>
<i class="flaticon-delete"
(click)="quizForm.get('questions').controls.splice(i,1) "
style="font-size: …Run Code Online (Sandbox Code Playgroud) 我尝试在我的应用程序中使用反应式表单。但是在更改组件期间,我收到“无法找到具有未指定名称属性的控件”错误。
我最初的 TypeScript 代码是:
onElementChange(): void {
this.activeData = this.getActiveData();
if (!this.activeData.isInitialized) {
this.activeData.filteredOptions = [];
this.activeData.formArray = new FormArray(this.activeData.zipElement.dimensionElements.map(() => {
const formControl = new FormControl();
this.activeData.filteredOptions.push(formControl.valueChanges.pipe(
startWith(''),
map((value: string | DimensionElement) => this.filter(value))
));
return formControl;
}));
this.setMatchedElements();
this.activeData.isInitialized = true;
}
}
Run Code Online (Sandbox Code Playgroud)
HTML代码是:
<cdk-virtual-scroll-viewport itemSize="36" id="scroll-container">
<li
*cdkVirtualFor="let element of getActiveData().zipElement.dimensionElements; let index = index"
[ngClass]="{ 'gray-row': index % 2 === 1 }"
class="dimension-element-item"
>
<div>
<span [matTooltip]="element.name" matTooltipPosition="above">
{{ element.name }}
</span>
</div>
<oc-drop-down
[containerGridClass]="'drop-down-grid'"
[content]="actions" …Run Code Online (Sandbox Code Playgroud) 我想用查询参数值初始化模板驱动的表单。
直观地,您将创建表单并填充它ngAfterViewInit:
HTML
<form #f="ngForm">
<input type="text" id="firstName" name="fname" #fname ngModel>
<input *ngIf="fname.value" type="text" id="lastName" name="lname" ngModel>
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
成分:
@ViewChild('f') f: NgForm;
constructor(private route: ActivatedRoute) {}
ngAfterViewInit() {
const queryParams = this.route.snapshot.queryParams;
this.f.form.setValue(queryParams)
}
Run Code Online (Sandbox Code Playgroud)
然后使用查询参数访问它: ?fname=aaa&lname=bbb
现在,这种方法有两个问题:
setValue将不起作用,因为第二个 ctrllname在应用值时不存在。这将需要我
patchValue只适用有效值,两次。就像是:
ngAfterViewInit() {
const queryParams = { fname: 'aaa', lname: 'bbb'};
// if we wish to access …Run Code Online (Sandbox Code Playgroud) angular ×10
angular-forms ×10
javascript ×2
angular5 ×1
angular6 ×1
angular7 ×1
html ×1
svg ×1
typescript ×1
unit-testing ×1
validation ×1