【问题标题】:(Unexpected behavior) Conditional two-way binding in Angular template [(ngModel)](意外行为)Angular 模板中的条件双向绑定 [(ngModel)]
【发布时间】:2021-07-13 11:29:37
【问题描述】:

当我在 Angular 中动态使用两种方式绑定时,我遇到了意外的行为, 类似[(ngModel)]="condition ? propA : propB"

更多详情,在我的app.component.ts

@Component({ ... })
export class AppComponent {
  props = { a: 'this is a', b: 'this is b' };
  myCondition = 'a';
}

还有我的模板:

<h2>props a: {{ props.a }} (type anything, last input will change)</h2>
<input #a [(ngModel)]="props.a" />
<hr>

<h2>props b: {{ props.b }}</h2>
<input #b [(ngModel)]="props.b" />
<hr>

<h2>last one (type anything, nothing happen)</h2>
<input #c [(ngModel)]="myCondition === 'a' ? props.a : props.b" />

我认为 input#c 应该更新了props.a,但什么也没发生。但是,在 input#a 中输入一些内容会触发 input#c 更改:(

谁能解释我发生了什么事?谢谢。

Stackblitz:https://stackblitz.com/edit/angular-ivy-emaszv

【问题讨论】:

    标签: angular


    【解决方案1】:

    你应该尝试这种绑定,像这样扩展它:

    [ngModel]="myCondition === 'a' ? props.a : props.b"
    (ngModelChange)="myCondition === 'a' ? props.a=$event : props.b=$event"
    

    这里是stackblitz

    More info here

    【讨论】:

    • 所以我的代码相当于``` [ngModel]='myCondition === "a" ? props.a : props.b' (ngModelChange)='myCondition === "a" ? props.a : props.b' ```对吗?
    • 不行,你必须根据ngModelChange中的条件将$event分配给props.a或b。
    猜你喜欢
    • 2020-09-12
    • 2019-01-02
    • 2017-04-29
    • 2017-08-28
    • 2016-10-12
    • 1970-01-01
    • 2017-03-23
    • 2019-10-26
    • 2017-10-20
    相关资源
    最近更新 更多