【问题标题】:angular component with multiple inputs and validation (required)具有多个输入和验证的角度组件(必需)
【发布时间】:2017-11-29 16:22:13
【问题描述】:

我想创建一个包含多个输入控件的自定义组件,我可以在其他组件表单中使用它,包括验证。我能找到的唯一示例展示了如何使用 ONE 输入和自定义验证器创建一个简单的组件。但我无法创建具有两个或更多输入的组件,例如

@Component({
    selector: 'stationDefaultProperties',
    template: '<div><span>Name:</span>
      <input [(ngModel)]="values.Name" (change)="onChanges()" name="name"  required maxlength="200" minlength="2" type="text">
      <span>Beschreibung:</span>
      <textarea [(ngModel)]="values.Beschreibung" name="beschreibung" minlength="4" type="text" rows="3"></textarea></div>',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => StationDefaultPropertiesComponent),
            multi: true
        }
    ]
})
export class StationDefaultPropertiesComponent implements ControlValueAccessor {
    @ViewChild('cF') public userFrm: NgForm;

    public values: my.Container.IStationDefaultProperties = {
        Aktiv: false,
        Beschreibung: "",
        Name: "",
        StationId: 0
    };

    constructor() { }

    public writeValue(value: my.Container.IStationDefaultProperties): void {
        if (value) {
            this.values = value;
            console.log(value);
        }
    }

    public onChanges(): void {
        this.propagateChange(this.values);
    }

    public registerOnChange(fn): void {
        this.propagateChange = fn;
    }

    public registerOnTouched(fn): void { }

    // the method set in registerOnChange to emit changes back to the form
    private propagateChange = (_: any) => { };
}

我正在使用“ControlValueAccessor”,以便可以使用“[(ngModel)]”调用我的组件

<form #f="ngForm" name="f" novalidate>
<stationDefaultProperties name="stdProperties" [(ngModel)]="viewModel && viewModel.DefaultProperties"></stationDefaultProperties>
 {{f.valid}} => is ALLWAYS TRUE
</form>

但问题是我不知道如何只为我的一个输入实现所需的验证器,并为它们两个实现最小长度验证器。该表单在开始时始终有效,但它不应该因为必填字段中没有值。

【问题讨论】:

    标签: angular angular-components angular-validation


    【解决方案1】:

    我在这篇文章中找到了一个很好的解决方案

    Angular2 nested template driven form

    还有一个指向一个要点的链接,其中包含有关解决方案的详细信息

    https://gist.github.com/jehugaleahsa/c40fb64d8613cfad8f1e1faa4c2a7e33

    该解决方案不使用“ControlValueAccessor”,我认为它对于我的这类问题来说是一个非常酷的解决方案,在自定义组件中有多个输入。

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      相关资源
      最近更新 更多