首页 > 解决方案 > 变量不会在视图中更新

问题描述

我想禁用所有button's, when selectedplaceis null,这在 Dialog 第一次启动时有效,但是当我更改选项时,它一直被激活。

这不应该是这样的,我在这里尝试过:

html:

      <label for="place">Einheit</label>
      <div class="input-group mb-3">
        <div class="input-group-prepend">
          <button class="btn btn-outline-secondary" [disabled]="!selectedplace" type="button">Change</button>
        </div>
        <select id="place" name="place" #place="ngModel" required class="form-control" [(ngModel)]="selectedplace" (change)="onDropdownChangeplace()">
          <option value=""></option>
          <option *ngFor="let i of UI_places" [ngValue]="i">{{i.name}}</option>
        </select>
        <div class="alert alert-danger" *ngIf="place.touched && !place.valid">Bitte eine Eingeben eingeben!</div>
        <div class="input-group-append">
          <button class="btn btn-outline-secondary" [disabled]="!selectedplace" type="button">Add</button>
          <button class="btn btn-outline-secondary" [disabled]="!selectedplace" type="button">Delete(red)</button>
        </div>
      </div>

打字稿(已声明):

public selectedplace: Place;

我该怎么办 ?

标签: angulartypescript

解决方案


你在做什么onDropdownChangeplace。我的猜测是您根据更改的索引分配一个值。

当您不分配值时(在空选择的情况下),之前的值仍然绑定到 ngModel。

在这里查看stackblitz。根据您的代码,它可以很好地启用和禁用。

这就是组件中的代码。我完全按照您发送的方式留下了 html。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
    public UI_places = [{id:0, name: 'home'},{id:1, name: 'work'}];
    public selectedplace: Place;

    onDropdownChangeplace() {

    }
}

推荐阅读