Maurice Wipf
Maurice Wipf

Reputation: 707

Updating variable in Angular component when another variable has changed

I try something like this:

component.ts

displayName: string;
email: string = `user+${this.displayName}@domain.com`;

component.html

<input type="text" [(ngModel)]="displayName" name="displayName">
<input type="email" [value]="email" name="email">

email is updated once when the app is loaded but not when displayName changes.

Do I need to use EventEmitter or ngOnChanges or anything else?

Upvotes: 3

Views: 4524

Answers (2)

Maurice Wipf
Maurice Wipf

Reputation: 707

I was able to solve it by using ngModelCange

component.ts

displayName: string;
email: string = null;

onKey(event: any) {
  this.email = (this.displayName === undefined || this.displayName === null) ? null : `user+${this.displayName}@domain.com`;
}

component.html

<input type="text" [(ngModel)]="displayName" (ngModelChange)="onKey($event)" name="displayName">
<input type="email" [value]="email" name="email">

You can also use keydown instead of ngModelChange. It has the same behaviour, at least in this case.

Upvotes: 0

tchelidze
tchelidze

Reputation: 8318

Reason is that displayName property is used to initialize email property value, hence consecutive reads of email property returns same value, no matter displayName is changed or not. instead what you need is to write a getter for email property and return value calculated based on displayName

Try following

get email(): string { return `user+${this.displayName}@domain.com`; }

Upvotes: 3

Related Questions