sravan ponugoti
sravan ponugoti

Reputation: 198

How to access the control directly by its formGroupName

In This form I have to access the control of formControlName="last" to show errors of it.

<div [formGroup]="form">
    <div formGroupName="name">
        <input formControlName="first" placeholder="First name">
        <input formControlName="last" placeholder="Last name">
        <span *ngIf="name['controls'].last.invalid">invalid</span>
    </div>
    <input formControlName="email" placeholder="Email">
    <button type="submit">Submit</button>
</div>

This code has thrown an error 'controls' of undefined(Bold Formatted line). control could be accessible by form['controls'].name['controls'].last.invalid , but is there any way I could access the control directly by its formGroupName ?

Thanks in Advance

Upvotes: 3

Views: 2827

Answers (3)

Jatin Patel
Jatin Patel

Reputation: 43

@sravanponugoti: we cannot use [formGroup] with in angular. Try this code

<form [formGroup]="form"> 
<div formGroupName="name"> 
<input formControlName="first" placeholder="First">
<input formControlName="last" placeholder="Last"> 
<span *ngIf="form.controls['name'].controls.last.valid">invalid</s‌​pan> 
</div> 
<input formControlName="email" placeholder="Email"> 
<button type="submit">Submit</button> 
</form>

Upvotes: 0

Jatin Patel
Jatin Patel

Reputation: 43

Could you try below snippet

<span *ngIf="form.get('last').invalid">invalid</span>

Upvotes: 1

Veena K. Suresh
Veena K. Suresh

Reputation: 1002

Try this

<div *ngIf="!form.controls.name.controls.last.valid">
       Invalid last name !!
    </div>

Upvotes: 1

Related Questions