【问题标题】:Having issue with Angular not updating the UI on model ChangeAngular 在模型更改时没有更新 UI 的问题
【发布时间】:2021-07-16 18:21:03
【问题描述】:

我对我的 Radiobox 组的 UI 更新有疑问。

<div  *ngFor="let options of dateOptions">
    <input class="form-check-input" [value]='options.value' (ngModelChange)="selectionChanged($event)" type="radio" name="dateOptions"
           [(ngModel)]="selectedOption">
    <label class="mr-3">
        {{options.displayText}}
    </label>
</div>

此绑定工作正常。我的组件扩展了 ControlValueAccessor 并且当selectedOption 更新如下:

writeValue(dateId: DateIds): void {
    const matchingOption = this.dateOptions.find((option) => equal(option.id, dateId))
    this.selectedOption= matchingOption ? matchingOption.value : this.selectedOption
    this.selectionChanged(this.selectedOption)
  }

selectedOption 的值设置正确,但 UI 仅在我与组件交互时才会更新。我不必更改选择,即使打开我的日期选择器就足以更新 UI。

根据文档,当selectedOption 更改以匹配值时,UI 应该更改。

【问题讨论】:

  • 您希望更新什么?输入还是标签?
  • 选中的单选按钮。
  • 请尝试将[value]='options.value' 替换为[value]="options.value"。我认为 HTML 中不允许使用单引号,除非它们被用作文本的一部分。由于一切都取决于value,也许这可以解决问题。
  • 很遗憾没有,但感谢您的建议

标签: angular typescript ngmodel controlvalueaccessor


【解决方案1】:

好的,我已经检查过了。您的想法按预期工作。您的代码中一定有一些东西干扰了更新过程。

这是我的设置。 10 秒后,selectedOption 的值发生更改。在我的情况下,单选按钮 1 失去选择,而 3 被选中。没有任何进一步的交互。

**HTML**

<div  *ngFor="let options of dateOptions">
    <input class="form-check-input" [value]='options' 
        (ngModelChange)="selectionChanged($event)" 
        type="radio" name="dateOptions"
        [(ngModel)]="selectedOption">
        <label class="mr-3">
            {{options}}
        </label>
 </div>

TS

dateOptions = ['date1', 'date2', 'date3'];
selectedOption = 'date1';


constructor() {
    setTimeout(() => {
        this.selectedOption = 'date3';
        console.log('changed');
    }, 10000);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2016-01-07
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多