如果表单中的错误计数大于1,我想有条件地应用css类.如何在angular4中执行此操作?
零件:
import { Component } from "@angular/core";
import { FormGroup, ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
@Component({
...
})
export class RegisterComponent {
complexForm : FormGroup;
constructor(fb: FormBuilder){
this.complexForm = fb.group({
'emailAddress' : [null, Validators.email],
'firstName': [null, Validators.compose([Validators.required, Validators.minLength(2)])],
...
})
}
submitForm(value: any){
console.log(value);
}
}
Run Code Online (Sandbox Code Playgroud)
模板:
<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
<section class="form-block">
<div class="form-group" [ngClass]="{'has-error':!complexForm.controls['emailAddress'].valid && complexForm.controls['emailAddress'].touched}">
<label for="formFields_1">Email Address</label>
<input [formControl]="complexForm.controls['emailAddress']" type="text" spellcheck="false" id="formFields_1" placeholder="" size="35">
<span *ngIf="complexForm.controls['emailAddress'].hasError('email') && complexForm.controls['emailAddress'].touched" class="tooltip-content">
Please enter a valid email address …Run Code Online (Sandbox Code Playgroud) 我有一个窗体控件,该控件在页面加载时会禁用。当用户单击一个按钮时,表单应启用编辑功能。但是,当我切换禁用控件的属性时,什么也不会发生。
模板
<form [formGroup]='accountForm'>
<md-input-container>
<input mdInput formControlName='name' />
</md-input-container>
<button (click)='isEditing = !isEditing'>Edit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
零件
export class AccountComponent {
private accountForm: FormGroup;
private isEditing = false;
private name: FormControl = new FormControl({ value: '', disabled: !isEditing;
constructor(
formBuilder: FormBuilder
) {
this.accountForm = formBuilder.group({
'name': this.name
});
});
}
Run Code Online (Sandbox Code Playgroud) 我不知道该怎么办
这是我的组件打字稿,带有新的FormGroup,然后是新的FormControls
this.trackerForm = new FormGroup({
session: new FormControl('', Validators.required),
date: new FormControl(new Date(), [
Validators.required
]),
contactType: new FormControl('', [
Validators.required
]),
customerType: new FormControl('', Validators.required),
firstName: new FormControl('', [Validators.required, Validators.minLength(80)]),
lastName: new FormControl('', [Validators.required, Validators.minLength(80)]),
phone: new FormControl('', [Validators.required, Validators.maxLength(10), Validators.minLength(10)]),
extension: new FormControl('', [Validators.maxLength(7)])
});
// this outputs the entire json
console.log(JSON.stringify(this.trackerForm.value));
//How do I ONLY console.log one of the values? date?
Run Code Online (Sandbox Code Playgroud)
页面上的HTML-
<form [formGroup]="trackerForm" (ngSubmit)="onSubmit(trackerForm.value)" novalidate>
<div>
<label class="form-control"><span>{{trackerForm.date.value}} </span></label>
</div>
Run Code Online (Sandbox Code Playgroud) 我的密码问题和在我的角应用程序中确认密码有问题.我正在使用被动表单,错误显示"提供的参数与呼叫目标上的任何签名都不匹配"
ngOnInit() {
this.form = this.formBuilder.group({
name: [null, [Validators.required, Validators.minLength(3)]],
email: [null, [Validators.required, Validators.email]],
password: [null, Validators.required],
confirm_password: [null, Validators.required],
}, {validator: this.passwordConfirming('password', 'confirm_password')});
}
passwordConfirming(c: AbstractControl): { invalid: boolean } {
if (c.get('password').value !== c.get('confirm_password').value) {
return {invalid: true};
}
}
Run Code Online (Sandbox Code Playgroud)
HTML
<div class="form-inline">
<label class="col-md-4">Password</label>
<input class="col-md-8" type="password" class="form-control" id="password" formControlName="password">
<span class="text-muted" *ngIf="!form.controls['password'].valid && form.controls['password']?.touched"> Password is required</span>
</div>
<div class="form-inline">
<label class="col-md-4">Confirm Password</label>
<input class="col-md-8" type="password" class="form-control" id="confirm_password" formControlName="confirm_password">
</div>
Run Code Online (Sandbox Code Playgroud) 我在弄清楚如何在用户输入/输入表单元素/值时同时显示它们时遇到问题。我希望在用户仍在输入且尚未按下提交按钮时显示它们。
json 管道允许我显示所有元素,但我无法弄清楚如何在 HTML 代码中显示单个元素。
{{commentForm.value | json}}
Run Code Online (Sandbox Code Playgroud)
我可以使用上述 JSON 管道访问所有元素,但想访问单个元素。
下面的示例 Angular Reactive Form 代码。
<form novalidate [formGroup]="commentForm" (ngSubmit)="onSubmit()">
<p>
<md-input-container class="full-width" dividerColor="{{formErrors.author ? 'warn': 'primary'}}" >
<input mdInput formControlName="author" placeholder="Name" type="text" required>
<md-hint>
<span [hidden] = "!(formErrors.author)">
{{formErrors.author}}
</span>
</md-hint>
</md-input-container>
<md-input-container class="full-width" dividerColor="{{formErrors.rating ? 'warn': 'primary'}}" >
<input mdInput formControlName="rating" placeholder="Rating" type="number" pattern="[0-5]*" required>
<md-hint>
<span [hidden] = "!(formErrors.rating)">
{{formErrors.rating}}
</span>
</md-hint>
</md-input-container>
<md-input-container class="full-width" dividerColor="{{formErrors.comment ? 'warn': 'primary'}}" >
<input mdInput formControlName="comment" placeholder="Your Comment" type="text" required> …Run Code Online (Sandbox Code Playgroud) 我有一个选择的反应形式
<select [(ngModel)]="user.positionId" name="positionId" class="custom-select form-control form-control-sm" required
formControlName="positionId"
[ngClass]="{
'is-invalid': positionId.invalid && (positionId.dirty || positionId.touched),
'is-valid': positionId.valid && (positionId.dirty || positionId.touched)
}">
<option value="">--Select--</option>
<option *ngFor="let position of user.positionSelectList" value="{{position.value}}">
{{position.text}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
它获得传递的positionId,它是可为空的数字
export class User{
id: string;
userName: string;
positionId?: number;
}
Run Code Online (Sandbox Code Playgroud)
当我将数字值作为positionId传递时,上述方法有效。
但是,当它传递一个空值时,则不会选择默认选项“ --Select--”,但是会在其上方显示一个附加的空白选项。
我尝试过的。
<option value=null>--Select--</option>
Run Code Online (Sandbox Code Playgroud)
和
<option value=udefined>--Select--</option>
Run Code Online (Sandbox Code Playgroud)
但这给出了与未选择“ --Select--”相同的结果
我不希望将硬编码数字值设置为固定数字,例如-1,因为我需要进行必要的验证,如果未选择,则需要空白值。
我观察formControl的valueChanges。表单控件是一个date picker。选择日期后,我会尝试将其重新格式化为yyyy-MM-dd原始MM-dd-yyyy格式。我直接修改表单控件的值。因此,它给了我递归调用错误。显然是真的。有什么解决办法吗?
代码:
this.parentForm.controls['myControlName'].valueChanges.subscribe((val)=>{
this.parentForm.controls['myControlName'].setValue(this._datePipe.transform(new Date(val), 'yyyy-MM-dd'));
});
<input #inputDate type="text" class="form-control" placeholder="Select date"
[formControl]="parentForm.controls['myControlName']"
[value]="selectedDate | date : 'MM-dd-yyyy'"/>
<datepicker [ngModel]="selectedDate" [minDate]="minDate"
[maxDate]="maxDate"
[showWeeks]="false"
[startingDay]="1"
(selectionDone)="onSelectionDone($event)">
</datepicker>
Run Code Online (Sandbox Code Playgroud)
错误:
例外:./ DatePickerComponent类DatePickerComponent中的错误-内联模板:13:8由以下原因引起:递归过多error_handler.js:54原始例外:递归过多
使用单选按钮在Angular中实现反应形式。我想设置一个默认值,我尝试了以下方法:
<form [formGroup]="form" (ngSubmit)="onSubmit(form)" class="actionsForm">
<input type="radio" id="entertainCrowdSkill1" [value]="skillsForBackend[0]"
class="radiobuttons" formControlName="skill" [checked]="true">
<input type="radio" id="entertainCrowdSkill2" [value]="skillsForBackend[1]"
class="radiobuttons" formControlName="skill">
</form>
Run Code Online (Sandbox Code Playgroud)
ngOnInit() {
this.form = this.fb.group({
skill: ['', Validators.required],
});
}
onSubmit(form) {
console.log(form.controls.skill.value) // logs empty string
}
Run Code Online (Sandbox Code Playgroud)
即使应用了CSS:checked课程,该按钮似乎也已选中。但是,当我尝试记录Skill的值时,它是一个空字符串(在fb中输入的默认值)。我已经看到了答案,但这是针对模板驱动的表单的。
如何以反应形式为模板中的单选按钮设置默认值?
我尝试导入FormsModule和NgForm模块,以及将FormsModule添加到imports数组。
下面是我的代码:
//our root app component
import { Component, NgModule, VERSION } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule, NgForm} from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form #searchForm="ngForm">
<input type="text" required [(ngModel)]="model.search" ngControl="search" #inputSearch="ngForm">
<p class="error" [hidden]="inputSearch.valid"> This input is required</p>
</form>
`,
styles: [`
.error {
color: red;
font-size: 11px;
}
`]
})
export class App {
public model = {
search: ""
}
constructor() {
}
}
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [App],
bootstrap: …Run Code Online (Sandbox Code Playgroud) 我有一个反应式
<form [formGroup]="secondFormGroup">
<ng-template matStepLabel>enter items</ng-template>
<div style="display: flex; flex-direction: column;">
<mat-form-field>
<input matInput type="text" placeholder="category" [(ngModel)]="newItem.CategoryName" formControlName="category"
/>
</mat-form-field>
<mat-form-field>
<input matInput type="text" placeholder="sub category" [(ngModel)]="newItem.SubCategoryName" formControlName="subCategory"
/>
</mat-form-field>
<mat-form-field>
<input matInput type="text" placeholder="product" [(ngModel)]="newItem.ProductName" formControlName="name"/>
</mat-form-field>
<mat-form-field>
<input matInput [(ngModel)]="newItem.Amount" type="number" min="0" placeholder="amount" formControlName="amount"
/>
</mat-form-field>
<mat-form-field>
<input matInput [(ngModel)]="newItem.Price" type="number" min="0" placeholder="price" formControlName="price"
/>
</mat-form-field>
<button mat-raised-button color="primary" (click)="AddNewProduct(newItem)" style="float: left; align-self: flex-end;">submit</button>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
我这样初始化:
this.secondFormGroup = this._formBuilder.group({
category: ['', Validators.required],
subCategory: ['', Validators.required],
name: ['', …Run Code Online (Sandbox Code Playgroud) angular angular-reactive-forms angular-forms angular-formbuilder
angular-forms ×10
angular ×9
javascript ×2
angular5 ×1
forms ×1
reactive ×1
recursion ×1
templates ×1