Search code examples
angularangular-forms

angular custom input for complex object


i have a object with 3 string members and I want to make a reusable input for it because it is used many times all over the application, so I'm trying to create a Custom Input that contains all 3 member's inputs. But i didn't found out a way, because other solutions that I've found don't let me to pass a complex object (MyObject) trough ngModel to my Custom Input component. To add complexity to my Question I need also to validate my Custom Input: if my custom input is required all of 3 sub-inputs are required. if one of sub-inputs gets filled the other 2 are required, if one of sub-inputs is invalid my Custom Input is invalid too.

Here an example of how I'd want my code to work (If possible)

MyObject.ts

export class MyObject {
    name: string;
    category: string;
    areaName: string;
}

MyFormComponent.ts

@Component({
    selector: 'app-my-form'
    template: `
     <form #myForm="ngForm">
       <my-object-input [(ngModel)]="myObj" ></my-object-input>
     </form>`
})
export class MyFormComponent {
    myObj: MyObject;
}

Thanks


Solution

  • I don't see any issues to solve your task by creating Custom Form Control. Follow this well-explained article custom-form-controls-in-angular-2. In this article you also can find the way of adding custom validation rules.

    The general idea is to implement ControlValueAccessor interface in your custom form control and add your logic inside the custom writeValue(value: any) method.