(click) 中的奇怪 angular 行为 - 如果设置为 false 值,则需要添加 'true;' 来更新 UI

Weird angular behaviour in (click) - need to add 'true;' to update UI if setting a false value

昨天在 angular 的单选按钮上卡了好久,也不是通常的“无法检查工作”的东西

基本上,如果我在(单击)函数中将变量设置为 false,UI 不会更新,但变量会更新(示例 angular html 代码如下使用 link - 尝试点击第一组是,然后不是...)

在第二组中,我必须向(单击)语句添加 'true;' 以使 UI 更新,即显示正确的单选按钮选择

第三组使用原始 type/javascript onclick 函数。变量不会更新(我不希望它更新),但是 UI 会使用与原始组相同的 'variable = false' 语句。

这是我应该知道的某种 angular 问题还是错误?

<p>Group 1, value = {{isYes}}</p>
<label>Nope<input type="radio" name="group1" id="nope" (click)="isYes = false;" checked></label>
<label>Yup<input type="radio" name="group1" id="yup" (click)="isYes = true;"></label>

<p>Group 2, value = {{isYes2}}</p>
<label>Nope<input type="radio" name="group2" id="nope2" (click)="isYes2 = false; true;" checked></label>
<label>Yup<input type="radio" name="group2" id="yup2" (click)="isYes2 = true;"></label>

<p>Group 3, value = {{isYes3}}</p>
<label>Nope<input type="radio" name="group3" id="nope3" onclick="this.isYes3 = false;" checked></label>
<label>Yup<input type="radio" name="group3" id="yup3" onclick="this.isYes3 = true;"></label>

https://stackblitz.com/edit/angular-ivy-lrte3r?file=src/app/app.component.html

Windows 10 Pro,Chrome 91(但在 Firefox 中也是如此)


编辑: 这仍然会正确地更新 UI,即使它 returns false for nope

<p>Group 3, value = {{isYes3}}</p>
<label>Nope<input type="radio" name="group3" id="nope3" onclick="return false;" checked></label>
<label>Yup<input type="radio" name="group3" id="yup3" onclick="return true;"></label>

这不是 Angular 皱纹。在第 1 组中,事件冒泡阻止它再次被更改。在第 2 组中,true 阻止它。理想情况下你会使用 JS Event#stopPropagation().

<p>Group 1, value = {{isYes}}</p>
<label>Nope<input type="radio" name="group1" id="nope" (click)="isYes = false; $event.stopPropagation();" checked></label>
<label>Yup<input type="radio" name="group1" id="yup"  (click)="isYes = true;"></label>

使用 vanialla JS 的第 3 组 onclick 无法识别 在 Angular 中使用时无法访问控制器变量(如 isYes3 = true),因此他们不会有任何影响。

我修改了Stackblitz


也就是说,Angular 中有更优雅、更高级的表单控制方式,您无需手动分配变量。查看 Angular forms overview.