【问题标题】:Bind text to a drop down list value on page load using angular 8使用角度 8 将文本绑定到页面加载时的下拉列表值
【发布时间】:2021-09-15 09:45:54
【问题描述】:

我在将值从数据库填充到 Angular 组件中的下拉列表时遇到问题。

从数据库中获取价值。当我在 html 页面中分配值时它不起作用。

代码:

public categoryList;

ngOnInit(): void {
    debugger;
    let adminid = localStorage.getItem('adminID');
    this.api.getAllCategories(adminid).subscribe(data => {
      console.log(data);
      this.categoryList = data;
    })
}

Html显示代码:

<div class="col-xl-6 col-md-6 col-12 mb-1">
  <div class="form-group">
    <h6>Choose Category<span style="color:red">*</span></h6>
    <!-- <input type="text" class="form-control" id="helpInputTop" /> -->
    <select class="form-control">
      <option [value]="item.CategoryName" *ngFor="let item of categoryList">
        {{item.CategoryName}}
      </option>
    </select>
    <span *ngIf="f.ChooseCategory.touched && f.ChooseCategory.invalid" class="invalid-form">
      <small class="form-text text-danger" *ngIf="f.ChooseCategory.errors.required">This field
        is required!</small>
    </span>
  </div>
</div>

下面是输出:

【问题讨论】:

标签: asp.net angular asp.net-web-api angular-ui-router


【解决方案1】:

试试这个!

categoryList: any[] = [];

constructor() {}

ngOnInit(): void {
    debugger;
    let adminid = localStorage.getItem('adminID');
    this.api.getAllCategories(adminid).subscribe(data => {
      console.log(data);
      this.categoryList = data;
    })
}

在html中

<select dropdown class="form-control">
      <option *ngFor="let item of categoryList" [value]="item.CategoryName">
        {{item.CategoryName}}
      </option>
    </select>

【讨论】:

    【解决方案2】:

    看来您使用的是常规 Array 而不是 Observable。

    尝试使用这种方法:

    //use a BehaviorSubject
    private _categoryList = new BehaviorSubject<any>([]);
    categoryList$ = this._categoryList.asObservable();
    
    constructor() {}
    
    ngOnInit(): void {
        debugger;
        let adminid = localStorage.getItem('adminID');
        this.api.getAllCategories(adminid).subscribe(data => {
          console.log(data);
          this._categoryList.next(data);
       })
      }
    
    

    并在您的 html 中使用 async 管道订阅该列表:

    ...
    <ng-container *ngFor="let item of categoryList$ | async">
     <option [value]="item.CategoryName">
       {{item.CategoryName}}
     </option>
    </ng-container>
    ...
         
    

    【讨论】:

    • 行为主体如何实现
    • 从 "rxjs" 导入 { Observable, BehaviorSubject };对吗?
    • 未显示相同的输出文本
    • 虽然使用异步管道实现被认为是好的做法,但对于 select 的工作并不强制
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多