【问题标题】:Cannot use ternary if statement inside [(ngModel)]不能在 [(ngModel)] 中使用三元 if 语句
【发布时间】:2025-12-03 11:50:02
【问题描述】:

尝试在 ngModel 中使用三元 if 语句。

<input [(ngModel)]="(mode == 'edit') ? userToUpdate.name_first : newUser.name_first" id="name_first" class="form-control" type="text">

表达式 (模式=='编辑')? userToUpdate.name_first : newUser.name_first 仅为 newUser.name_first 绑定模型,但不将模型绑定到 userToUpdate.name_first。

这是我尝试使用该语句的地方: https://github.com/alex-chaliy/TeamManager/blob/master/client/src/app/home/home.component.html#L43

【问题讨论】:

标签: angular


【解决方案1】:

它应该如何工作?这种表达没有意义。当输入值更新时,Angular 如何理解模型上的哪个值应该更新?您应该改用 getter/setter。

get firstName(): string {
    return (mode == 'edit') ? this.userToUpdate.name_first : this.newUser.name_first;
}
set firstName(val: string) {
    if(mode === 'edit') this.userToUpdate.name_first = val;
    else this.newUser.name_first = val;
}

PS。我不太喜欢我给你的解决方案,因为你的组件应该知道用户是否是新用户这一事实告诉我设计很糟糕。您最好将其作为来自上述组件的组件的输入参数,并让更高的组件传递现有的用户对象或新的空对象。

【讨论】:

    【解决方案2】:

    我刚刚在两种模式下都使用了“userToWrite”变量解决了这个问题。

    【讨论】: