角度5:在两个选择字段中验证匹配

时间:2018-11-20 10:52:09

标签: angular typescript validation angular-forms

我在基于Angular 5的应用中使用ng-select。我有两个选择字段,并且如果第一个选择中的值与第二个选择中的值匹配,我需要显示错误并阻止提交按钮。

ng-select模块具有选项compareWith,但是我不确定是否应该使用它。我也有@angular/forms的验证人。

如何验证选择的字段以匹配值?

example.html

<form [formGroup]="form" *ngIf="form">
    <section class="sidebar-container with-footer">
        <article>

            <h3>Ports</h3>

            <div class="row">
                <label>Load port</label>
                <ng-select [items]="ports$ | async"
                    bindLabel="name"
                    bindValue="id"
                    [placeholder]="!loadPort.portId ? 'Select a port' : ''"
                    (change)="onChange(1, $event)"
                    [virtualScroll]="true"
                    formControlName="port"
                    >
                </ng-select>
            </div>

            <div class="row">
                <label>Disport</label>
                <ng-select [items]="ports$ | async"
                    bindLabel="name"
                    bindValue="id"
                    [placeholder]="!voyage.voyagePoints[1].portId ? 'Select a port' : ''"
                    (change)="onChange(2, $event)"
                    [virtualScroll]="true"
                    formControlName="port"
                    >
                </ng-select>
            </div>
        </article>
    </section>
</form>
<footer class="sidebar-footer button-group">
    <button class="button button-default"
            type="button"
            qa-id="new-voyage-open-vessel-selection"
            [disabled]="!form.valid"
            (click)="submit()">
        Submit
    </button>
</footer>

example-component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { FormGroup, FormControl, Validators, AbstractControl, ValidatorFn, FormBuilder, ValidationErrors } from '@angular/forms';


@Component({
    selector: 'app-component',
    templateUrl: './app-component.component.html',
    styleUrls: ['./app-component.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

    ports$: Observable<Port[]>;
    form: FormGroup;

    constructor(
        private fb: FormBuilder
    ) { }

    ngOnInit() {

    }

    onChange(type: any, port: any) {

    }

    private createForm() {
        const groups = {};

        this.voyage.voyagePoints.forEach((point, index) => {
            const group: Dictionary<FormControl> = { port: this.fb.control(point.portId, [Validators.required]) };
            groups['point' + index] = this.fb.group(group);
        });

        this.form = this.fb.group(groups);
    }

}

0 个答案:

没有答案