首页 文章

具有多个输入和验证的角度分量(必需)

提问于
浏览
0

我想创建一个带有多个输入控件的自定义组件,我可以在其他组件表单中使用它,包括验证 . 我能找到的唯一例子展示了如何使用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>

但问题是我不知道如何只为我的一个输入和两个minlength验证器实现所需的验证器 . 表单在启动时始终有效,但不应该因为必填字段中没有值 .

1 回答

相关问题