Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
Maurice Wipf Avatar asked Nov 15 '25 18:11

Maurice Wipf


1 Answers

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`; }
like image 186
tchelidze Avatar answered Nov 17 '25 08:11

tchelidze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!