4
votes

So I've been reading how to construct custom FormControls in Angular2, but I can't get what I'm trying to do working fully with validation. I have a normal input control that I want to wrap up in a custom Component so that I can do this:

<my-control name="something" [(ngModel)]="model.something" required></my-control>

Rather than repeating this every time:

<div class="form-group has-feedback" [ngClass]="{'has-success': someInput.valid, 'has-error': someInput.invalid && someInput.dirty}">
    <label class="control-label" for="someId">{{label || 'Some Input'}}</label>
    <input type="test" class="form-control" id="someId" placeholder="Some Input" [ngModel]="value" (ngModel)="onChange($event)" name="someInput" required #someInput="ngModel" minlength="8"/>
    <span class="glyphicon form-control-feedback" aria-hidden="true" [ngClass]="{'glyphicon-ok': someInput.valid, 'glyphicon-remove': someInput.invalid && someInput.dirty}"></span>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.required" class="text-danger">Some Input is required</div>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.minlength" class="text-danger">Some Input must be at least 8 characters</div>
</div>

So I've implemented by custom Component following articles about how to create custom components online:

https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

What's missing is the ability to move the validation out of the component, but allow the custom component to handle the display of that validation. So if you look above what I'm going for is to allow validation to be specified by the user of the component rather than have the component impose specific validations (note some validation would be inherent to a component, for example an email address component would validate it's an email without the user specifying that). Notice that required is placed on the usage of that customer component.

So how do I get a reference to the custom component's FormControl within that component's definition? NOTE: I understand how to access the input field within the template's FormControl instance as my code above demonstrates that exactly. What I'm asking for is the FormControl instance for the custom control that template is within. In the article I reference it would be the FormControl for the CounterInputComponent.

1

1 Answers

1
votes

Adding this seems to work:

@ViewChild(NgModel) model: NgModel;

Then you can get to your FormControl through:

this.model.control