首页 > 解决方案 > 在 Angular 中绑定数据后,Select 根本不显示

问题描述

我正在尝试将国家数据绑定到注册表单中的选择选项中,但绑定后选择完全消失了。这是代码:

数据模型

export class Countries {
    public name: string;
    public code: string;

    constructor(name: string, code: string) {
      this.name = name;
      this.code = code;

    }
  }


  export const country: Countries [] = [
    {
        "name": "United States",
        "code": "US"
    },
    {
        "name": "Netherlands",
        "code": "NL"
    },
    {
        "name": "United Kingdom",
        "code": "UK"
    },
]

我剪切了整个数据,因为这里显示太长了。但它看起来像这样。

打字稿

import {country} from "../../models/countries.model"

...
export class SignupComponent implements OnInit {
country[];
 SignupForm: FormGroup;
...
ngOnInit() {
 this.nav.hide(); 
 this.SignupForm = new FormGroup({
       'username': new FormControl(null, [Validators.required,
      Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])'),
       ]),
      'password': new FormControl(null, [Validators.required,
      Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}'),
       ]),
       'country': new FormControl([Validators.required,
         ]),
    });
}

我认为错误应该在 TypeScript 中。这里也是 HTML 部分:

HTML

  <div class="form-group form-signup">
      <input class="form-control form-control-lg" placeholder="Password" type="password" formControlName="password"/>
      <span *ngIf="!SignupForm.get('password').valid && SignupForm.get('password').touched" class="help-block">Please enter a valid password!</span>
  </div>
  <div class="form-group form-signup">
        <select class="form-control form-control-lg" *ngFor="let countries of country" [value]="countries.name" formControlName="country">
                <option value="">--Please choose an option--</option>
            <option>   {{ countries.name }}
        </option>
        </select>
        <span *ngIf="!SignupForm.get('country').valid && SignupForm.get('country').touched" class="help-block">Please enter a country!</span>
  </div>

怎么了?为什么 Select 完全消失并且绑定不起作用?如何解决?

标签: angularangular6angular-forms

解决方案


你必须重复option标签而不是select标签:

<select class="form-control form-control-lg">
       <option value="">--Please choose an option--</option>
       <option  *ngFor="let countries of country" [value]="countries.name" formControlName="country">  {{ countries.name }}  </option>
</select>

问候,


推荐阅读