Angular Material Mat-Select ngModel布尔值无法工作

3

我在Angular 7项目和Angular Material中使用mat-select来选择用户的性别。

原始回答: Original Answer

 <mat-form-field>
          <mat-select placeholder="Gender" required 
            formControlName="isMale" 
            [(ngModel)]="userProfile.isMale">
            <mat-option value="false">Women</mat-option>
            <mat-option value="true">Men</mat-option>
          </mat-select>
          <mat-hint align="end">Please Select...</mat-hint>
          <mat-error *ngIf="isControlHasError('isMale','required')"><strong>Please Select Gender</strong>
          </mat-error>
        </mat-form-field>

从服务器获取用户资料,其中isMale属性是布尔类型,但在获取数据后,在mat-select上不显示所选值。我也尝试了这种方法,但不起作用。

最初的回答:

        <mat-option [value]="'false'">Women</mat-option>
        <mat-option [value]="'true'">Men</mat-option>

最初的回答,但它不起作用。
4个回答

11

这对我有用(我正在使用Angular 8)

   <mat-form-field>
    <mat-select [(ngModel)]="userProfile.isMale">
      <mat-option [value]="true">Men</mat-option>
      <mat-option [value]="false">Women</mat-option>
    </mat-select>
  </mat-form-field>

请注意,我在没有任何单引号的情况下使用了[value] = "true or false"。 显然,userProfile.isMale应该是布尔值(true或false)。


2

看起来你同时在使用formControlName和[(ngModel)]。在Angular 7中,我们不能同时使用这两个。所以可能这就是为什么你的ngModel不起作用的原因。

你可以使用以下方法来获取选定的值:

最初的回答

formName.controls['isMale'].value;

您可以像这样将值设置为此表单控件:
最初的回答:您可以使用以下方式设置此表单控件的值:
formName.controls['isMale'].setValue(true);

在这里,formName是您的formGroup名称。最初的回答。

感谢您的回答。我已经移除了FormControlName,只使用ngModel,但是没有起作用。我还尝试了移除ngModel,并添加了this.postForm.controls['isMale'].setValue(userProfile.isMale);但仍然没有起作用。我还尝试了将True或False传递给this.postForm.controls['isMale'].setValue(),包括'True'和'False',但是仍然没有起作用。 - undefined
如果您只使用[(ngModel)],那么您必须设置name属性,才能使其正常工作。 - undefined
最终我使用了这个代码:this.postForm.controls['isMale'].setValue(profile.isMale?'true':'false'); 在从服务器获取模型后手动设置mat-select并将布尔值转换为字符串,但我认为可以将布尔值绑定到mat-select。 - undefined

0
     <mat-option value="true"> Yes </mat-option>
     <mat-option value="false"> No </mat-option>

它将以字符串形式返回类似于IsApplicable="true"

     <mat-option [value]="true"> Yes </mat-option>
     <mat-option [value]="false"> No </mat-option>

this [value]="true" returns IsApplicable=true as string value

这个 [value]="true" 返回字符串值为IsApplicable=true。

     <mat-option [ngValue]="true"> Yes </mat-option>
     <mat-option [ngValue]="false"> No </mat-option>

使用 [ngValue] 返回布尔值


-2
最后我使用了this.postForm.controls['isMale'].setValue(profile.isMale?'true':'false');在从服务器获取模型后手动设置mat-select并将布尔值转换为字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接