[英]How to make a mat-select list have an option automatically selected
The list is binded to the .ts code: Here is the html :该列表绑定到 .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>
How do i make one of the options automatically selected when i open the page?如何在打开页面时自动选择其中一个选项?
I'd make a direct edit to your code, but you didnt provide much, so here goes a very simple example:我会直接编辑你的代码,但你没有提供太多,所以这里有一个非常简单的例子:
This is your ts
file这是你的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);
}
}
This is your html
file:这是你的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>
As you can see, you just take the people
object ( FormGroup instance
) and set its value to whatever you want.如您所见,您只需获取people
对象( FormGroup instance
)并将其值设置为您想要的任何值。 I couldn't make it more trivial then this.我不能让它更微不足道了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.