首页 > 解决方案 > 更改检测后角度视图不更新

问题描述

我有一个下拉列表,我想动态禁用它,我正在使用 @Input 从父组件获取值并在子组件中禁用它。

@input 值正确返回并在 ngOnchange 上触发,我已经控制了 @input 值,它按预期返回。

但是,当我在 HTML 上打印该值时,该值不会随 onChange 更新。(组件中的值发生变化,模板没有更新)

我已经尝试过 this.ref.detectChanges() 和 ngZone 仍然无法正常工作

HTML

<div ngbDropdown #commonDropdown="ngbDropdown" class="d-inline-block" style="width: 100%;" [autoClose]="true">
      <button class="btn btn-primary truncate" id="dropdownBasic1" ngbDropdownToggle [disabled]="disableChannel">
        {{values.selected.value}}
      </button>
      <div ngbDropdownMenu aria-labelledby="dropdownBasic1" style="width: 100%;">
        <button *ngFor="let value of values.data" class="dropdown-item" (click)="selectDropDown(value); commonDropdown.close();">{{value.value}}
        </button>
      </div>
</div>

零件 :

export class CommonComponent implements OnInit, OnChanges {
      @Input()
      disableChannel: boolean;
      @Input()
      values: DropDownObject;
      @Output()
      valueSelected: EventEmitter < any > = new EventEmitter();
      private selectedValues: DropDownObject;

      constructor(private ref: ChangeDetectorRef, private ngZone: NgZone) {

      }

      ngOnInit() {
        this.emitSelectedValue(this.values);
      }

      ngOnChanges(simpleChanges: SimpleChanges) {
        console.log(this.disableChannel);
        // boolean returns as expected however, binding in the view doesn't work. Button is not disabled when the value returns true
      }


      selectDropDown(selectedChannel): void {
        this.values.setSelected(selectedChannel);
        this.selectedValues = new DropDownObject();
        this.selectedValues.setSelected(selectedChannel);
        this.selectedValues.setData(this.values.getData());
        this.emitSelectedValue(this.selectedValues);
      }

      emitSelectedValue(data) {
        this.valueSelected.emit(data);
      }

}

标签: angulartypescriptng-bootstrap

解决方案


推荐阅读