4

I have a lot of boilerplate code on my templates that follow roughly this structure.

<div class="form-group col-lg-6"
     [ngClass]="{'has-error': errors?.startDate || !startDate.valid}">
    <label>Start Date</label>
    <input class="form-control"
           [(ngModel)]="currentEntity.startDate"
           #startDate="ngModel" name="startDate"
           required />
    <small *ngIf="!startDate.valid" class="help-block">
        Start Date Is Required
    </small>
    <small *ngIf="errors?.startDate" class="help-block">
        {{errors.startDate}}
    </small>
</div>

The second error block is for any server validations that come back.

I was hoping to make a directive that could just be something like <validatedInput [inputName] = "startDate" /> and replace the key elements in each property. Is there anyway to dynamically change things like #startDate="ngModel" to #{{inputName}}="ngModel". ngIf would also have to be set up dynamically.

I'm running "@angular/forms": "0.1.1".

2
  • 1
    Have a look into the Angular 2 formbuilder. Using that I think you might be able to achieve what you are looking for. Commented Jul 7, 2016 at 1:30
  • 2
    Template variables are static-only. You can't name them dynamically. Commented Jul 7, 2016 at 3:45

1 Answer 1

1

Template reference variables are static as Günter pointed out. However, using Angular 2 formbuilder you may not need them any longer.

In your component you can create the form group like this: (Note: formbuilder needs to be injected into your component constructor.)

this.myForm = this.formBuilder.group
({
    "startDate": [currentEntity.startDate, Validators.required],
    ...
});

and modify your html to something like this:

<div class="form-group col-lg-6" [ngClass]="{'has-error': errors?.startDate || !startDate.valid}">
      <label>Start Date</label>
      <input class="form-control" [formControl]="myForm.controls['startDate']" name="startDate" />
      <small *ngIf="!myForm.controls['startDate'].valid" class="help-block">
       Start Date Is Required
       </small>
    ...

I am using the form syntax from RC4 here. Furthermore, you might be able to iterate over the FormGroup array and create multiple such controls via an *ngFor. (In order to do so you may need a temporary array into which to extract the relevant info from FormGroup).

Another advantage of FormGroups is the fact that their elements are Observables which allows you to do all kinds of interesting things.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.