Darion Badlydone
Darion Badlydone

Reputation: 947

Angular 2 get input validation status

I'm creating an input text component with angular2. I need to add a class at this control if is valid and if it's required. This is the component:

import { Component, Input  } from "@angular/core";
import { NgForm }    from '@angular/forms';

@Component({
    selector: "input-control",
    template: `
        <div [class.has-success]="required" class="form-group form-md-line-input form-md-floating-label">
            <input [class.edited]="model[property]"
                [(ngModel)]="model[property]"
                [attr.ngControl]="property"
                [name]="property"
                type="text"
                class="form-control"
                id="{{property}}"
                value=""
                [attr.required]="required">
            <label [attr.for]="property">{{label}}</label>
            <span class="help-block">{{description}}</span>
        </div>
        `
})
export class InputControlComponent {

    @Input()
    model: any;

    @Input()
    property: string;

    @Input()
    label: string;

    @Input()
    description: string;

    @Input()
    required: boolean;

    @Input()
    form: NgForm;

}

In the first row of the template I set the "has-success" class if the input is required but I need to set it if it's valid too. Somethig like this:

[class.has-success]="required && form.controls[property].valid"

The html is this:

<form role="form" *ngIf="active" (ngSubmit)="onSubmit(databaseForm)" #databaseForm="ngForm">
    <div class="form-body">
        <div class="row">
            <div class="col-md-6">
                <input-control [model]="model" [property]="'code'" [form]="databaseForm" [label]="'@Localizer["Code"]'" [description]="'@Localizer["InsertCode"]'" [required]="true"></input-control>
            </div>
            <div class="col-md-6">
                <input-control [model]="model" [property]="'description'" [form]="databaseForm" [label]="'@Localizer["Description"]'" [description]="'@Localizer["InsertDescription"]'"></input-control>
            </div>
        </div>
    </div>
</form>

Upvotes: 1

Views: 1262

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202276

I think that you can't use the template-driven form a sub-component and make it be part of a form of the parent component without implementing a custom value accessor with Angular2 prior to version RC2.

See this question:

With version RC2+, I think that it's possible out of the box like this:

<form #databaseForm="ngForm">
  <input-control name="code" [ngModelOptions]="{name: 'code'}"
                 [(ngModel)]="model.code"/>
</form>

Upvotes: 1

Related Questions