gpt4 book ai didi

angular - 使用 [(ngModel)] 与 HTML 中的字符串值绑定(bind)

转载 作者:搜寻专家 更新时间:2023-10-30 21:16:14 28 4
gpt4 key购买 nike

我有一个 Material 滑动切换按钮,它使用 [(ngModel)] 与值为“true”或“false”的字符串变量进行双向绑定(bind),当我切换它时,按钮会正确更新变量的值,但是当它第一次加载到 DOM 中时,即使变量中的值为“false”,它也始终显示其状态为 true。

<div *ngIf="agent.attributes[i].type == 'Boolean'">
<mat-slide-toggle [checked]="agent.attributes[i].value == 'true' ? true : false"
[(ngModel)]="agent.attributes[i].value">{{agent.attributes[i].value}}</mat-slide-toggle>
</div>

this is the result

最佳答案

您正在将字符串值绑定(bind)到需要 bool 值以进行检查的 ngModel,因此将其更改为:

<div>
<mat-slide-toggle
[checked]="agent.attributes[i].value === 'true' ? true : false"
(change)="setValue( i , $event )">
{{agent.attributes[i].value}}
</mat-slide-toggle>
</div>

代码:

setValue(i , e){
if(e.checked){
this.agent.attributes[i].value = 'true'
}else{
this.agent.attributes[i].value = 'false'
}
}

DEMO

关于angular - 使用 [(ngModel)] 与 HTML 中的字符串值绑定(bind) <mat slide toggle>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53812445/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com