Snowman
Snowman

Reputation: 2495

Edit form field labels in angular 2

I have a built a model-driven (reactive) form, as shown here, in Angular 2.

My html looks like this:

<form [formGroup]="userForm" (ngSubmit)="onSubmit(userForm.value, userForm.valid)">
    <label for="firstName">First Name:</label>
    <input type="text" formControlName="firstname" id="firstName" required>

    <label for="lastname">Last Name:</label>
    <input type="text" formControlName="lastname" id="lastName" required>

    <br>

    <label for="email">Email:</label>
    <input type="email" formControlName="email" id="email">

    <br>
</form>

In my .ts file:

import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
...

ngOnInit() {
    this.paymentForm = this.formBuilder.group({
        firstname: ['', Validators.required],
        lastname: ['', Validators.required],
        email: ['',],


    })

    this.userForm.valueChanges.subscribe(value => {
        console.log(value);           
    });
}

I've added the required attribute in my template as well, as suggested by angular docs

Quoting:

required remains, not for validation purposes (we'll cover that in the code), but rather for css styling and accessibility.

What I want is to cycle through each form field and add a * to the associated label if the field is required.

So, First Name reads First Name *; and so on.

How would I go about doing that. Thanks.

Upvotes: 1

Views: 1691

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657268

@Directive({
  selector: '[required]'
})
export class LabelRequiredDirective {
  constructor(private elRef:ElementRef){}

  ngAfterContentInit() {
    this.elRef.nativeElement.labels.forEach(l => l.textContent += ' *');
  }
}

Because the selector matches every element that has the required attribute, it is applied to all elements where the label should be updated.

Sadly nativeElement.labels is only supported in Chrome. For other browsers another strategy is necessary to get the label associated with an input element (See also Find html label associated with a given input)

Upvotes: 1

Related Questions