Angular 2,设置默认值以选择选项

时间:2016-09-27 12:03:19

标签: javascript angular angular2-forms

我尝试为选项添加默认值。它就像一种占位符,我用this method来做。 在纯HTML中它可以工作,但是如果我尝试使用{2}属性的角度2属性,它就不会选择任何东西。

这是我在纯HTML中使用的代码:

var fs = require('fs');
var path = require('path');

module.exports = function (router) {
    router.get('/file-list', function (req, res) {
        var getFiles = function (callback) {
            var rootDir = path.join(__dirname, 'views');

            walk(rootDir, function (err, results) {
                if (err) {
                    console.log(err);
                    return;
                }

                markup(results, callback);
            });

        };

        var walk = function (dir, done) {
            var results = [];

            fs.readdir(dir, function (err, list) {
                if (err) {
                    return done(err);
                }

                var pending = list.length;

                if (!pending) {
                    return done(null, results);
                }

                list.forEach(function (file) {
                    file = path.resolve(dir, file);

                    fs.stat(file, function (err, stat) {
                        if (stat && stat.isDirectory()) {
                            walk(file, function (err, res) {
                                results = results.concat(res);

                                if (!--pending) {
                                    done(null, results);
                                }
                            });
                        } else {
                            results.push(file);

                            if (!--pending) {
                                done(null, results);
                            }
                        }
                    });
                });
            });
        };

        var markup = function (files, callback) {

            var items = [];
            for (i = 0; i < files.length; i++) {
                var q = files[i];

                q = q.slice(0, -5);
                var markup = '<li>' + '<a href="' + q + '">' + q + '</a>' + '</li>';
                items.push(markup);
            };
            callback(items);
        };

        getFiles(function (items) {

            // render markup for items
            res.render('file-list', {
                'files': items
            });
        });
    });
};

使用Angular模板:

*ngFor

班级

  <select name="select-html" id="select-html">
    <option value="0" selected disabled>Select Language</option>
    <option value="1">HTML</option>
    <option value="2">PHP</option>
    <option value="3">Javascript</option>
  </select>

我希望 <select name="select" id="select" [(ngModel)]="selectLanguage"> <option *ngFor="let item of selectOption" [selected]="item.value==0" [disabled]="item.value==0">{{item.label}}</option> </select> 被选为默认值。它被禁用但未被选中。

如何选择默认值?

Live example

4 个答案:

答案 0 :(得分:22)

<强>更新

4.0.0-beta.6添加了compareWith

<select [compareWith]="compareFn"  [(ngModel)]="selectedCountries">
    <option *ngFor="let country of countries" [ngValue]="country">
        {{country.name}}
    </option>
</select>

compareFn(c1: Country, c2: Country): boolean {
   return c1 && c2 ? c1.id === c2.id : c1 === c2;
} 

这样,分配给selectedCountries的实例不需要是相同的对象,但可以传递自定义比较函数,例如,以便能够匹配具有相同属性值的不同对象实例。

<强>原始

如果要将对象用作值,则需要在选项元素上使用[ngValue]

  <select name="select" id="select" [(ngModel)]="selectLanguage">
    <option *ngFor="let item of selectOption" [ngValue]="item"
      [disabled]="item.value==0">{{item.label}}</option>
  </select>

selectLanguage分配了[(ngModel)]="..."的选项值时,此选项会默认选中一个:

import {Component} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-form-select',
  templateUrl: 'default.component.html'
})
export class DefaultComponent {
  private selectOption: any;
  constructor() {
    this.selectOption = [
      {
        id: 1,
        label: "Select Language",
        value: 0
      }, {
        id: 2,
        label: "HTML 5",
        value: 1
      }, {
        id: 3,
        label: "PHP",
        value: 2
      }, {
        id: 4,
        label: "Javascript",
        value: 3
      }
    ];
    this.selectLanguage = this.selectOption[0];
  }
}

答案 1 :(得分:14)

我发现从selectOption数组中删除默认选项并单独指定默认的不可选选项会更好。

<select name="select" id="select" [(ngModel)]="selectLanguage">
  <option [ngValue]="undefined" disabled>Select Language</option>
  <option
         *ngFor="let item of selectOption"
         [value]="item.value"
  >
    item.label
  </option>
</select>

答案 2 :(得分:4)

请尝试以下示例代码:
yourValue替换为您要选择默认值

的值
<select  placeholder="country" >
       <option *ngFor="let country of countriesList" [ngValue]="country" [selected]="country.country_name == yourValue" >
             {{country.country_name}}
       </option>
</select>

答案 3 :(得分:1)

<select class="form-control" [(ngModel)]="someList.key" name="key"  #key="ngModel" required>
     <option value="undefined" selected disabled>Select option</option>
     <option *ngFor="let data of someList" value="{{data.key}}">{{data.key}</option>
 </select>