【问题标题】:Selecting default value of option as a model in angular选择选项的默认值作为角度模型
【发布时间】:2018-12-12 03:22:48
【问题描述】:

我有一个咖啡馆模型,我想将其显示为咖啡馆列表中的默认值。这是我的代码

<div class="form-group">
    <label for="theme" style="margin-top: 20px;">Cafe Name</label>
    <select class="form-control" [ngModel]="cafeList" (ngModelChange)="changeCafe($event)" name="cafe">
        <option *ngFor="let cafe of cafeList" [ngValue]="cafe">{{cafe.name}}</option>
    </select>

    <a href="" style="margin-top: 10px;"  [routerLink]="['/cafe/edit-cafe', selectedCafe.cafeId]" class="btn btn-warning">
        <i class="ti-comment pdd-right-5"></i>
        <span>View Cafe</span>
    </a>
</div>   

为了检索数据,我正在做这样的事情

const data   = d[0];
this.ad =  <AdsItem> data.payload.val();
this.selectedCafe = this.ad.cafe;
this.cafeId = this.ad.cafe.cafeId;

this.subscription = this.db.list<CafeItem>('cafeList').snapshotChanges().subscribe(d=>{          
    this.cafeList = [];
    d.forEach(data =>{
        var user =  <CafeItem> data.payload.val();
        this.cafeList.push(user);
    });           
});        

现在我不确定如何将 selectedCafe 设置为默认咖啡馆

【问题讨论】:

  • ngModel 应该是字符串而不是数组

标签: angular angular6


【解决方案1】:

你有两个问题

  1. 您的ngModel 应该是选择过程中未列出的字符串,角度会将该字符串更改为您的选项值
  2. [ngValue]="cafe"绑定对象作为值无效,因为浏览器会将其呈现为ng-reflect-ng-value="[object Object]"

将您的选择代码更改为:

<select class="form-control" [ngModel]="cafeModel" (ngModelChange)="changeCafe($event)" name="cafe">
        <option *ngFor="let cafe of cafeList" [ngValue]="cafe.name">{{cafe.name}}</option>
    </select>

并在打字稿中分配cafeModel默认值

这里是demo

【讨论】:

    【解决方案2】:

    在带有单个值的 select 标记中使用 ngModel 来显示默认值,并且每当您更改选项时它也会更新 selectedCafe 变量,因为它是双向绑定。

    <select class="form-control" [(ngModel)]="selectedCafe"(ngModelChange)="changeCafe($event)" name="cafe">
            <option *ngFor="let cafe of cafeList" [ngValue]="cafe">{{cafe.name}}</option>
        </select>
    

    【讨论】:

      【解决方案3】:

      &lt;select class="form-control" [(ngModel)]="selectedCafe" name="cafe" style="width: 250px"&gt; &lt;option *ngFor="let cafe of cafeList" [ngValue]="cafe"&gt;{{ cafe }}&lt;/option&gt; &lt;/select&gt;


      .ts 文件: 咖啡馆列表 = [1, 2, 3, 4]; selectedCafe = 2;

      请相应地修改您的代码,希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-19
        • 1970-01-01
        • 2022-11-26
        • 1970-01-01
        • 2018-03-07
        • 2022-11-28
        • 2020-08-07
        相关资源
        最近更新 更多