为什么默认值不在 Mat Select 下拉列表中呈现?



我对 Angular 相当陌生,但除非我从我的 Mat Select(用于我的 GraphQL 突变(中删除 ngModel,否则它不会呈现默认值。我的目标是让下拉列表预先填充用户的当前位置。

<mat-list-item>
<mat-form-field>
<mat-label>Location</mat-label>
<mat-select [value]="user.position" matNativeControl required [(ngModel)]="newLocation">
<mat-option value="Top">Top</mat-option>
<mat-option value="Front">Front</mat-option>
<mat-option value="Middle">Middle</mat-option>
<mat-option value="Back">Back</mat-option>
<mat-option value="Right">Right</mat-option>
<mat-option value="Left">Left</mat-option>
</mat-select>
</mat-form-field>
</mat-list-item>

这是 TS 文件:

updateUser(userId) {
this.apollo
.mutate({
mutation: EDIT_USER,
variables: {
input: {
userPosition: this.newLocation,
}
}
})
.subscribe(
({ data }) => {
if (data['editUser'].complete) {
this.getAssets();
const user = this.assetDetails.users.find((s) => s.id === userId);
user.userPosition = this.newLocation;
}
},
(error) => {}
);
}

我已经验证了user.position给了我正确的值,因为它在删除[(ngModel(]="newLocation"后就会呈现,但就像我之前说的,我的突变需要它。我似乎想不出解决方法。感谢任何意见。

只需删除matNativeControl[(ngModel)]绑定即可。在此之后,预定义值将起作用(如果user.position值等于任何选项值。这区分大小写(。

您应该使用ngModel 或 Value,而不是同时使用两者。

我在其他答案的帮助下想通了:

我基本上必须在ngModel(newLocation(中将值设置为在突变之前保存初始值的变量,而不是将新值设置为"newLocation"。这样,它将呈现初始/默认值。然后,我将该变量作为参数传递给我的突变。

以下是更新代码的片段:

<mat-list-item>
<mat-form-field>
<mat-label>Location</mat-label>
<mat-select [value]="user.position" matNativeControl required [(ngModel)]="user.userPosition">
<mat-option value="Top">Top</mat-option>
<mat-option value="Front">Front</mat-option>
<mat-option value="Middle">Middle</mat-option>
<mat-option value="Back">Back</mat-option>
<mat-option value="Right">Right</mat-option>
<mat-option value="Left">Left</mat-option>
</mat-select>
</mat-form-field>
</mat-list-item>

然后我像这样调用我的函数:

updateUser(user.id, user.userPosition)

和 TS:

updateUser(userId, position) {
this.apollo
.mutate({
mutation: EDIT_USER,
variables: {
input: {
userPosition: position,
}
}
})
.subscribe(
({ data }) => {
if (data['editUser'].complete) {
this.getAssets();
const user = this.assetDetails.users.find((s) => s.id === userId);
user.userPosition = position;
}
},
(error) => {}
);
}

ngModel 和 value 不能同时使用,因为 ngModel 优先。

最新更新