Jhansi ravula
Jhansi ravula

Reputation: 51

How to populate the values of one field to another field in angular?

here I'm trying to set fullName and userName to be same. "UserName" is readonly. when I'm entering values in FullName field, simultaneously, the userName field also should get field. I.e, my Fulname and UserName should be same.Could anyone help me do it. https://stackblitz.com/edit/angular-11-form-validation-g6vxne?file=src%2Fapp%2Fapp.component.html

Upvotes: 0

Views: 4470

Answers (2)

N Fard
N Fard

Reputation: 1099

change your second input to be like this :

<input
    [value]="form.get('fullname').value"
    type="text"
    formControlName="username"
    class="form-control"
    [ngClass]="{ 'is-invalid': submitted && 
    f.username.errors }"
/>

Upvotes: 2

tomek550
tomek550

Reputation: 470

Try this:

this.form.get("fullname").valueChanges.subscribe((change)=>this.form.get("username").setValue(change));

This subscribes to valueChange event of fullaneme formfield, and applies changes to username field.

Also I think it's bad to have different validation on username and fullname, as full name might not actually meet username validation requirements. I can also imagine 2 persons with same full name, trying to register to some website :).

Upvotes: 2

Related Questions