3

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?

Maurice Wipf
  • 647
  • 2
  • 7
  • 13

2 Answers2

3

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`; }
tchelidze
  • 8,050
  • 1
  • 29
  • 49
0

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.

Maurice Wipf
  • 647
  • 2
  • 7
  • 13