我尝试这样的事情:
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
在应用加载时更新一次,但在displayName
更改时则不会更新。
我是否需要使用EventEmitter
或ngOnChanges
或其他任何内容?
答案 0 :(得分:1)
原因是email
属性用于初始化 email
属性值,因此displayName
属性的连续读取返回相同的值,无论{{1是否改变了。相反,您需要为email
属性编写一个getter,并根据 displayName
尝试以下
get email(): string { return `user+${this.displayName}@domain.com`; }
答案 1 :(得分:0)
我可以使用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">
您也可以使用keydown
代替ngModelChange
。它具有相同的行为,至少在这种情况下。