如何在Angular 2反应形式中设置下拉(选择 - 选项)输入的默认值

时间:2017-04-14 06:45:48

标签: angular typescript

我有一个对象的下拉列表。它是一个人物对象,其属性为public class AdsServiceTest: IDisposable { private readonly DbContextOptions<SensingSiteDbContext> _options; private readonly SensingSiteDbContext _context; private readonly AdsService _AdsService; public AdsServiceTest() { //initialize db options _options = new DbContextOptionsBuilder<SensingSiteDbContext>() .UseInMemoryDatabase() .Options; //get service _context = new SensingSiteDbContext(_options); //initialize dbcontext List<Ads> listAds = new List<Ads>() { new Ads(){ Id=1,AdsName="Ads1", Deleted=false}, new Ads(){ Id=2,AdsName="Ads2", Deleted=false}, new Ads(){ Id=3,AdsName="Ads3", Deleted=false} }; //In the second test method, it throw errors, listAds already exist in _context.Advertisements.AddRange(listAds); _context.SaveChanges(); BaseLib.SSDbContext<Ads, AdsService> ssDbContent = new BaseLib.SSDbContext<Ads, AdsService>(_context); _AdsService = ssDbContent.GetService((x, y) => new AdsService(x, y)); } public void Dispose() { _context.Dispose(); } [Theory] [InlineData(1)] public void FindById(int id) { Ads adsResult = _AdsService.FindById(id); Ads adsTarget = _context.Advertisements.Find(id); Assert.Equal(adsResult.AdsName, adsTarget.AdsName); //Assert.True(adsTarget.Equals(adsResult)); } [Fact] public void GetAll() { var adsResult = _AdsService.GetAll(); var adsTarget = _context.Advertisements.ToList(); Assert.Equal(adsResult.Count(),adsTarget.Count()); //Did not work all the time //Assert.True(adsTarget.Equals(adsResult)); } } idfirstName

lastName

让&#39;说我有一个对象的人,我想检查我的这个人对象是否在下拉列表中。如果存在,我希望该对象人员成为下拉列表的选定选项/默认值。

2 个答案:

答案 0 :(得分:2)

您可以使用formControl并使用它设置默认值。根据您是否具有组件初始化的值,可以在构建表单时设置值,否则在收到值时使用patchValue。因此,当您构建表单时(如果您有数据)

ngOnInit() {
  this.myForm = this._fb.group({
    person: [this.persons[1]]
  }); 
}

Demo

PS,通常我们不会在这里使用ngValue,这会绑定整个对象,但当然这也适用于你想要/需要做的事情:)

答案 1 :(得分:0)

不使用ngModel的方法。您也可以使用* ngFor内每次迭代的索引(i)选择下拉列表的默认值。您可以在option元素上使用'selected'属性,然后将index(i)的值设置为您要使其默认的选项。在这里,我已经选择了默认选择的第二个选项。 Index是数组中每个选项的索引。 下面是相同修改的代码:

@Component({   选择器:'my-app',   模板:`                           {{option.name}}                

相关问题