选择选项的默认值作为角度模型

时间:2018-12-12 03:22:49

标签: angular angular6

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

<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设置为默认咖啡馆

3 个答案:

答案 0 :(得分:0)

您有两个问题

  1. 您的Notice: Undefined variable: file_path in C:\laragon\www\web3\index.php on line 33 Warning: include_once(C:\laragon\www\web3\views): failed to open stream: Permission denied in C:\laragon\www\web3\index.php on line 33 Warning: include_once(): Failed opening 'views/' for inclusion (include_path='.;C:/laragon/etc/php/pear') in C:\laragon\www\web3\index.php on line 33 应该是一个不在选择过程中列出的字符串,Angular会将其更改为您的选项值
  2. ngModel绑定对象作为值无效,因为浏览器会将其呈现为[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> 默认值

这是demo

答案 1 :(得分:0)

在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>

答案 2 :(得分:0)


  

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


.ts文件: cafeList = [1,2,3,4]; selectedCafe = 2;

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