不能使用[(ngmodel)]内部的if ternary



尝试用用户ternary if语句ngmodel中的语句。

<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/src/src/home/home/home.component.html#l43

它应该如何工作?这种表达没有意义。当输入值更新时,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。我真的不喜欢我给您的解决方案,因为您的组件应该知道用户是否是新手的事实告诉我,设计很糟糕。您最好将其作为输入参数从上方的组件中作为组件,并让较高的组件通过现有用户对象或新的空对象。

我刚刚使用两种模式的'usertowrite'变量解决了问题。

最新更新