Angular选择初始值



我想在材料选择中有默认/初始值。我尝试添加[(value)]= initialValue,[value]=initialValue。但它们不起作用。我在表格中列出了一些建筑。每个建筑都有几个侧翼(我把建筑分成几个部分,就像在医院里,你把建筑分成不同的部分)。我使用select do show all wings of building,这样用户就可以选择他想要的那个。但是我希望在用户选择之前我有默认值。

<mat-form-field  *ngIf="getSpecificPodZg(element.key).length" >
<mat-label>Podzgrada</mat-label>
<mat-select [(value)]="selectedPod"  [(ngModel)]="is_selected[i]" disableOptionCentering class="mySelectClass">
<mat-option *ngFor="let zgrada of getSpecificPodZg(element.key)" [value]="zgrada.key" required >
{{zgrada.ime}}
</mat-option>
</mat-select>
</mat-form-field>

和函数

的ts文件
getSpecificPodZg(zg_idd:String){

this.SpecificPodZg=[];
this.PodZgrada.forEach((element: any) => {
if(element.zg_id==zg_idd){
this.SpecificPodZg.push(element);
}
});
return this.SpecificPodZg;

try also this: with [selected]

<mat-form-field  *ngIf="getSpecificPodZg(element.key).length" >
<mat-label>Podzgrada</mat-label>
<mat-select   [(ngModel)]="is_selected[i]" disableOptionCentering class="mySelectClass">
<mat-option *ngFor="let zgrada of getSpecificPodZg(element.key); let i = index" [value]="zgrada.key" [selected]="i===0"  >
{{zgrada.ime}}
</mat-option>
</mat-select>
</mat-form-field

要给一个字段赋一个默认值,你必须先用ngModel把它绑定到一个变量:

<mat-form-field  *ngIf="getSpecificPodZg(element.key).length" >
<mat-label>Podzgrada</mat-label>
<mat-select [(ngModel)]="initialValue">
<mat-option *ngFor="let zgrada of table" [value]="zgrada.key" required >
{{zgrada.ime}}
</mat-option>
</mat-select>
</mat-form-field>

然后在.ts文件中分配一个初始值(默认值必须从用于创建mat-option元素的相同数组中分配):

table = [{ime: "...", "key": "..."}, {ime: "...", "key": "..."}, {ime: "...", "key": "..."}]
initialValue = table[0].key

首先:

[(value)]="selectedPod" 
[(ngModel)]="is_selected[i]"

下面是什么?你试着绑定两个不同的变量,如果我没理解错的话。在此之上,mat-option value指向一个特定的属性[value]="zgrada.key", select value/ngModel绑定也应该指向同一个属性,否则在initial select之后可能会显示空白。

我建议使用响应式表单来处理mat-form-field中的数据。然后,您可以在ngOnInit中轻松订阅表单更改并输出数据,以便您可以跟踪更改。粗略的示例(您需要将ReactiveFormsModule包含到您的模块中,并将表单相关的导入包含到实际的组件中):

foo.component.html:

<form [formGroup]="myForm">
...
<mat-form-field  *ngIf="getSpecificPodZg(element.key).length" >
<mat-label>Podzgrada</mat-label>
<mat-select formControlName="myListField" disableOptionCentering class="mySelectClass">
<mat-option *ngFor="let zgrada of getSpecificPodZg(element.key)" [value]="zgrada.key" required >
{{zgrada.ime}}
</mat-option>
</mat-select>
</mat-form-field>
...
</form>

foo.component.ts:

myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.myForm = this.fb.group({
myListField: initial_value_here // here you put initial value to a select field, needs to be the same as value of option you want to pick; myListField is a formControlName used with mat-select
});
// listening to form changes
this.myForm.valueChanges.subscribe(c => {
console.log('form changes', c);
});
}

最新更新