I want to create a custom component with multiple input controlls which I can use in other components forms including the validation. The only examples I could find show how to create a simple component with ONE input and a custom validator. But I was not possible to create a component with two or more inputs like
@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) => { };
}
I am using the "ControlValueAccessor" so that I can call my component with "[(ngModel)]"
<form #f="ngForm" name="f" novalidate>
<stationDefaultProperties name="stdProperties" [(ngModel)]="viewModel && viewModel.DefaultProperties"></stationDefaultProperties>
{{f.valid}} => is ALLWAYS TRUE
</form>
but the problem is I don't know how to implement the required validator for only one of my inputs and a minlength validator for both of them. The form is allways valid on start, but it shouldn't because there is no value in the required field.
I've found a great Solution in this post
Angular2 nested template driven form
and there is a link to a gist which contains a detailed information about the solution
https://gist.github.com/jehugaleahsa/c40fb64d8613cfad8f1e1faa4c2a7e33
The solution don't uses the "ControlValueAccessor" and I think its a really cool solution for my kind of problem, with multiple inputs in a custom component.