2017-06-26 26 views
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> 

但問題是我不知道如何實現所需的驗證器只有我的一個輸入和他們兩個最小長度驗證。表單在開始時是有效的,但不應該是因爲在必填字段中沒有值。

回答