标签: angular-forms

通过 Switch Case 进行 Angular ReactiveForm 错误处理

我有一个反应式表单,其中我使用 ngif 验证不同的字段。

例如:

  <mat-form-field>
  <input  matInput formControlName="name" placeholder="Name">
  <mat-error 
  *ngIf="personForm.get('name').hasError('required')">Name is 
   empty</materror>
  <mat-error *ngIf="personForm.get('name').hasError('minlength')">Needs more 
   than 3 characters</mat-error>
  </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

是否有可能在 switch case 语句中做同样的事情以及如何继续这样做?

我想象了这样的事情

validateErrors {
  switch(errorHandling) {
  case 1: 'Name is empty';
  case 2: 'Needs more than 3 characters';
  }
}
Run Code Online (Sandbox Code Playgroud)

如何让 mat-errors 显示这些不同的情况?任何指导将不胜感激,谢谢!

error-handling switch-statement angular angular-reactive-forms angular-forms

2
推荐指数
1
解决办法
2702
查看次数

具有多个字段的 Angular 模板驱动表单验证

假设我有一个带有一些字段的简单表单(Stackblitz 示例):

@Component({
  selector: 'my-app',
  template: 
`
<h1>AppComponent</h1>

<form>
  <h2>UserData</h2>
  <userdata [user]="model.userData"></userdata>

  <h2>Actions</h2>
  <actionbar ></actionbar>
</form>
`,
})
export class AppComponent  { ... }

@Component({
  selector: 'userdata',
  template: 
`
<span class="status {{name.status}}">{{name.status}}</span>
full name:
<input name="name" #name="ngModel" pattern="^.* .*$" required [(ngModel)]="user.name">
<br>

<h3>--- Contacts ---</h3>

<span class="status {{email.status}}">{{email.status}}</span>
email:
<input name="email" #email="ngModel" type="email" [email]="true" [(ngModel)]="user.contacts.email">
<br>


<span class="status {{phone.status}}">{{phone.status}}</span>
phone:
<input name="phone" #phone="ngModel" pattern="^[0-9]*$" [(ngModel)]="user.contacts.phone">
<br>


<h4>---- Address ----</h4>

<span class="status {{street.status}}">{{street.status}}</span>
street:
<input name="street" #street="ngModel" [(ngModel)]="user.contacts.address.street">
<br> …
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular-forms

2
推荐指数
1
解决办法
4808
查看次数

如何在 html 视图中显示表单控件的值?

我知道这听起来非常简单,但我无法让它发挥作用。我知道我必须使用小胡子标签来显示它,但当我在表单字段中输入内容时它不会显示。这是我的代码:

<label>Variety name: {{seedForm.get('varietyName').value}}</label>
Run Code Online (Sandbox Code Playgroud)

这是实际的表单域:

<mat-form-field>
    <mat-label>Variety name</mat-label>
    <input matInput name="variety" type="text" placeholder="The name of the variety" autofocus
        formControlname="varietyName" required>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

这是种子形式的定义:

this.seedForm = fb.group({
  'varietyName' : ['', Validators.required]
})
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这段代码不显示我输入的值。谁能告诉我我做错了什么?

谢谢。

angular angular-forms

2
推荐指数
1
解决办法
4352
查看次数

输入字段上的 Angular 条件只读/禁用

我有一个包含输入字段的表,我正在其中填充模型值,我想对这些填充的字段应用只读/禁用。当我单击添加行时,我将空行添加到表中。添加到表中的空行必须是可编辑的。我无法找到仅对已填充的表格单元格应用只读/禁用的逻辑。

超文本标记语言

<table>
<thead>
    <th> Name </th>
    <th> Age </th>
    <th> Url </th>
    <th> Gender </th>
    <th> Image </th>
    <th> Keywords </th>
</thead>
<tbody>
    <tr *ngFor="let data of userList; let $index = index">
        <td> <input class="form-control" type="text" id="userListName"[(ngModel)]="userList[$index].name"
            name="userListName{{$index}}" [readonly]="userList[$index].name.length"/></td>
        <td> <input class="form-control" type="text" id="userListAge" [(ngModel)]="userList[$index].age"
            name="userListAge{{$index}}" readonly/></td>
        <td><input class="form-control" type="text" id="userListUrl" [(ngModel)]="userList[$index].url" name="userListUrl{{$index}}" readonly/></td>
        <td> <input class="form-control" type="text" id="userListGender" [(ngModel)]="userList[$index].gender"
            name="userListGender{{$index}}" readonly/></td>

        <td> <input class="form-control" type="text" id="userListImage" [(ngModel)]="userList[$index].image"
            name="userListImage{{$index}}"  readonly/>
        </td>
        <td> <input class="form-control" type="text" id="userListKeywords" [(ngModel)]="userList[$index].keywords"
            name="userListKeywords{{$index}}" readonly/></td> …
Run Code Online (Sandbox Code Playgroud)

html javascript typescript angular angular-forms

2
推荐指数
1
解决办法
2万
查看次数

如果至少一个字段具有值,则向反应式 FormGroup 的所有控件添加所需的验证

我有一个几乎没有控件的表单组,仅当至少一个字段具有值时才需要所有字段。即,任一用户都可以将所有字段保留为空或在所有字段中输入数据。每个控件都需要经过验证才能在其下方显示所需的错误。

我尝试在内置所需验证器的帮助下为此构建自定义验证器,但它仅验证当前控制。

allFieldRequired(ctrlName: string): ValidatorFn {
    return (ctrl: AbstractControl) => {
      if (!ctrl.parent || !Object.values(ctrl.parent.value).join('')) {
        return null;
      }
      return CustomValidators.required()(ctrl)
    }
  }
Run Code Online (Sandbox Code Playgroud)

是我的实现。

typescript angular angular-reactive-forms angular-forms

2
推荐指数
1
解决办法
2536
查看次数

Angular 6 FormArray 和 HTML 中的循环

全部,

我很难让 FormArray 与我当前的应用程序一起工作。我正在尝试从服务中获取姓名并将其添加到预订表单中(并赋予用户添加/删除/修改姓名的能力)

这是相关代码:

reservationForm: FormGroup;
attendeeArray: FormArray;

constructor(
  private groupMeetingService: GroupMeetingsService,
  private formBuilder: FormBuilder
) {}

ngOnInit() {
  this.initialize();
}

private createAttendeeName(name: string): FormControl {
  return this.formBuilder.control({
    name: name
  });
}

private initialize(): void {
  this.attendeeArray = this.formBuilder.array([]);
  this.reservationForm = this.formBuilder.group({
    attendeeRadio: ['inPerson'],
    attendeeName: this.attendeeArray,
  });

  this.groupMeetingService.getMeeting(this.meeting.id).subscribe(meeting => 
  {
    this.meetingLocation = meeting.location;
  });
  this.groupMeetingService
    .getReservations(this.meeting.id)
    .subscribe(data => {
      this.reservations = data;
      this.attendeeArray = this.getAttendeeNames();
      data.attendees.forEach(attendee => {
        this.attendeeArray.push(this.createAttendeeName(attendee.name));
      });
      console.log('array', this.reservationForm);
  });
}
Run Code Online (Sandbox Code Playgroud)

当我查看控制台时,它确实显示它正在被添加。上面的代码正确吗?

如果它是正确的,我如何在 HTML 中循环它并让它显示?

我尝试了很多东西但没有运气:-( …

ngfor angular angular-forms formarray

2
推荐指数
1
解决办法
7202
查看次数

如何使 Angular Reactive Form 也需要禁用输入?

我有一个输入,当用户单击对话框时将填充该输入。因此,为此我必须将其禁用,因为我不希望用户手动输入该值。唯一的问题是这个输入必须是必需的,而我到目前为止还做不到。

我尝试在输入中添加“required”指令,并尝试在创建表单时添加 Validator.required,但这些都没有成为表单所需的字段。

createUnityForm(): FormGroup {
    return this._formBuilder.group({
        id      : [this.unity.id],
        description: [this.unity.description],
        floor: [{value: this.unity.floor, disabled: true}, Validators.required]
    });
}

<mat-form-field appearance="outline" floatLabel="always" class="mr-16" fxFlex>
    <mat-label>{{'UNITY.FLOOR' | translate}}</mat-label>
    <input matInput placeholder="{{'UNITY.SELECT-FLOOR' | translate}}"
        name="floor"
        formControlName="floor"
        required>
</mat-form-field>

<button *ngIf="action === 'edit'"
    mat-button
    class="save-button"
    (click)="matDialogRef.close(['save',unityForm])"
    [disabled]="unityForm.invalid"
    aria-label="save">
        {{'GENERAL.SAVE' | translate}}
</button>
Run Code Online (Sandbox Code Playgroud)

即使输入中没有任何内容,unityForm 也是有效的

angular angular-reactive-forms angular-forms angular-validator

2
推荐指数
1
解决办法
9773
查看次数

我的自定义表单控件上收到“validators.map 不是函数”错误

我创建了一系列组件用作表单控件ControlValueAccessor。当应用formControlName,formGroupNameformGroupArray我的组件传递表单控件时,我收到错误消息

validators.map 不是一个函数

这就是我的组件的设置方式

@Component({
  selector: 'view-box-form-component',
  templateUrl: './view-box-form.component.html',
  styleUrls: ['./view-box-form.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(()=>ViewBoxFormComponent),
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(()=>ViewBoxFormComponent)
    }
  ]
})

export class ViewBoxFormComponent implements OnInit, ControlValueAccessor {

  ViewBoxFormData: FormGroup;

  constructor() { }

  ngOnInit() {}

  public onTouched : ()=> void =()=>{};

  writeValue(val: any):void{ val && this.ViewBoxFormData.setValue(val, {emitEvent: false}); console.log(val); }

  registerOnChange(fn: any): void{ this.ViewBoxFormData.valueChanges.subscribe(fn); console.log(fn); }

  registerOnTouched(fn: any): void{ this.onTouched = fn; }

  setDisabledState?(isDisabled: …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-forms

2
推荐指数
1
解决办法
1185
查看次数

异步验证器 (AsyncValidatorFn) 从不订阅

我写了一个自定义的表单验证器,但errors它只是有"_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": {"_isScalar": false}, "operator": {}}, "operator": {"total": 1}并且表单永远不会有效。

这是我的验证器:

export function asyncEmailValidator(): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return of(control.value).pipe(
      map(res => {
        return res && res.indexOf('example.de') < -1 ? { eMailUnavailable: true } : null;
      }),
      take(1), finalize(() => {})
    );
  };
}
Run Code Online (Sandbox Code Playgroud)

这是我如何使用它:

emailFormControl = new FormControl('', [
  Validators.required,
  Validators.email,
  asyncEmailValidator()
]);
Run Code Online (Sandbox Code Playgroud)

从调试中,我发现我检查 example.de 的地图块从未到达过,我不明白为什么。在显示内部返回之前使用和输出函数本身。

我在网上的多个示例中看到了这种结构,但它似乎对我不起作用。

我在用 @angular/forms 10.0.14

angular angular-reactive-forms angular-forms angular2-form-validation

2
推荐指数
1
解决办法
834
查看次数

将图像转换为 Angular 中的字节数组(打字稿)

我有一个要求,需要将所选图像(表单组的一部分)转换为字节数组,该数组需要作为发布请求的一部分发送到后端。

HTML 组件:

<div class="form-group">
                <label>Image</label>
                <input type="file" accept="image/*" class="form-control" formControlName="productImage" onchange="displaySelectedImageFunc(this);">
                <img *ngIf="displaySelectedImage" src="{{selectedImageUrl}}">
                <span class="error-message" *ngIf="itemRegistrationForm.controls.productImage.dirty && itemRegistrationForm.controls.productImage.errors">Select Image of the product</span>
</div>
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-forms

2
推荐指数
1
解决办法
2万
查看次数