首页 > 解决方案 > 如何使垫选择列表自动选择一个选项

问题描述

该列表绑定到 .ts 代码:这是 html :

                        <mat-label>Тип на апликација:</mat-label>
                        <mat-select [(value)]="AppId" required #apptype="ngModel" [(ngModel)]="AppId" name="apptype" 
                            >
                            <mat-option>---</mat-option>
                            <mat-option  *ngFor="let applicationType of applicationTypes"  value="applicationType.ID" >
                                {{applicationType.Name}}
                            </mat-option>
                        </mat-select>
                        <mat-error *ngIf="apptype && apptype.touched && apptype.errors && inputForm.submitted">
                            <span *ngIf="apptype.errors['required']">Ова поле е задолжително.</span>
                        </mat-error>
                    </mat-form-field>

打开页面时如何自动选择其中一个选项?

标签: javascripthtmlangularangular-material

解决方案


我会直接编辑你的代码,但你没有提供太多,所以这里有一个非常简单的例子:

这是你的ts文件

@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  people: FormGroup;

  peopleArray=[{
    name:'name 1',
  },{
    name:'name 2',
  },{
    name:'name 3',
  }]

  constructor(private fb: FormBuilder){}

  ngOnInit() {

        this.people = this.fb.group({
            people: [null, Validators.required]
        });

    const toSelect = this.peopleArray.find(p => p.name == "name 3");
    this.people.get('people').setValue(toSelect);
    }
}

这是你的html文件:

<form [formGroup]="people">
<mat-form-field class="full-width">
    <mat-select placeholder="person" formControlName="people">
        <mat-option>--</mat-option>
        <mat-option *ngFor="let person of patientCategories" [value]="person">
            {{person.name}}
        </mat-option>
    </mat-select>
</mat-form-field>

<p>{{people.get('people').value | json}}</p>
</form>

如您所见,您只需获取people对象 ( FormGroup instance) 并将其值设置为您想要的任何值。我不能让它比这更微不足道。


推荐阅读