【问题标题】:How to default select the first item in multiple select field in Angular?如何在Angular的多个选择字段中默认选择第一项?
【发布时间】:2021-06-20 00:30:32
【问题描述】:

我制作了一个 Stackblitz 应用程序,我在其中使用了一个选择框,可以进行多项选择。我想始终默认选择第一项,但我无法实现。

我正在使用 selected ="i==0" 但这没有帮助。

<select multiple class="custom-select" formControlName="cityName">
              <option *ngFor="let city of City ;let i= index;" [ngValue]="city" [selected]="i==0" (change)="changeCity($event)">{{city}}</option>
            </select>

这是 stackblitz 链接 -

https://stackblitz.com/edit/angular-multi-select-dropdown-reactive-forms?file=src%2Fapp%2Fapp.component.html

谁能帮我解决这个问题?

【问题讨论】:

    标签: angular


    【解决方案1】:

    你可以试试这个:

    registrationForm = this.fb.group({
        cityName: [[this.City[0]], [Validators.required]]
    });
    

    选择是多重的,所以为了预先选择一些选项,需要用数组来设置表单值。在这个数组中,你只需推送第一个城市:this.City[0]

    如果您从服务中获取数据,那么您可以这样做:

    registrationForm: FormGroup;
    cities = City[] = [];
    
    constructor(private myService: MyService) {
      registrationForm = this.fb.group({
        cityName: [[], [Validators.required]]
      });
    
      this.myService.getCities().subscribe(cities => {
        this.cities = cities;
        this.registrationForm.get('cityName').patchValue([].concat(cities[0]))
      });
    }
    
    

    在这个例子中,getCities() 必须返回一个 Observable&lt;City[]&gt; 类似 Http 请求,或者类似 of(['Florida', 'South Dakota', 'Tennessee', 'Michigan', 'New York']) 的东西

    【讨论】:

    • 非常感谢。有效 。如果我可以问一下,如果 City 数组稍后从组件中的服务填充,我该怎么办?
    • @AnandSrivastava 我已经编辑了我的帖子,请检查
    • 哇,好用。现在需要研究一下patchValue。太感谢了 。你让我的生活更轻松。
    • 超级!你可以在这里找到一些信息 -> angular.io/guide/…
    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多