Angular 7 compareWith 可以与模式一起使用吗?

Angular 7 can compareWith be used with a modal?

抱歉,如果这是重复的! 所以我试图让我的 mat-select 默认为列表中的第一个选项。听起来很简单,对吧?错误的。我正在使用弹出的模式输入任务并尝试设置默认状态(一旦项目 selected,你只能 select )。 compareWith 函数工作得很好,但是一旦退出模式并重新进入(不刷新页面),compareWith 函数中的第二个参数为 null 并且状态不会默认任何事情。退出表格时,我将其重置。我使用的是 FormControl,而不是 ngModel,仅供参考。

我尝试了几种不同的 compareWith 函数,但只找到了一种有效的方法。我曾尝试在 select 标签上使用 [selected]="whatever",但通过研究很快发现它不适用于 material 输入。我还尝试在重置表单时将 formcontrol 值设置为等于状态。这行得通,但是当我再次打开模式时它已经显示出来了。由于在项目 selected 之前状态处于禁用状态,因此我不想在加载时显示任何状态。

html 中的项目 select:

<mat-form-field class="form-group">
      <mat-select id="project" name="project" placeholder="Project" formControlName="project" [required]="true"
        [ngClass]="{'is-invalid': formAddTask.project.errors}">
        <mat-option *ngFor="let project of availableProjects" [value]="project.id">{{project.name}}</mat-option>
      </mat-select>
      <mat-error *ngIf="addTaskForm.get('project').hasError('required')">Project is required</mat-error>
    </mat-form-field>

状态 select 在 html:

 <mat-form-field class="form-group">
      <div class="input-group"></div>
      <mat-select id="status" name="status" placeholder="Status" formControlName="status" [compareWith]="compareObjects">
        <mat-option *ngFor="let status of availableStatuses; let i = index" [class.selected]="status === selectedStatus" 
         [value]="status.id">{{status.name}}</mat-option>
      </mat-select>
    </mat-form-field>

ts 中的 CompareWith 函数:

compareObjects(o1: any, o2: any): boolean {
return o1.name === o2.name && o1._id === o2._id;
}

如果还有什么需要展示的,请告诉我!

在项目 selected 之前状态不应该有任何内容,一旦发生这种情况,我希望状态默认为列表中的第一个选项。实际发生的是,一旦模式退出并返回,默认状态将在 selecting 项目后不再显示,或者它将显示在模式的初始加载时,我希望它只项目 selected 后显示默认值。

抱歉,如果我重复了太多的话,我宁愿提供太多信息也不愿提供足够的信息。在此先感谢,任何帮助表示赞赏! :)

蝙蝠的第一件事,是的,[compareWith]绝对可以用于modals

要解决此问题,请使用 [(value)] 而不是 [value] 并将其绑定到 status 而不是 status.id。这意味着,compareWith 将获得 select 值和 option 值作为 status 对象,而您拥有的比较函数将获得 ids和来自这些对象的 names 并进行比较。

 <mat-form-field class="form-group">
      <div class="input-group"></div>
      <mat-select id="status" name="status" placeholder="Status" formControlName="status" [compareWith]="compareObjects">
        <mat-option *ngFor="let status of availableStatuses; let i = index" [class.selected]="status === selectedStatus" 
         [(value)]="status">{{status.name}}</mat-option>
      </mat-select>
    </mat-form-field>

所以我最终找到了解决方法。我在项目下拉列表中添加了一个 onChange 事件,并在那里设置了状态下拉列表的值。

这是我最终使用的代码:

onProjectChange() { this.addTaskForm.get('status').setValue(this.availableStatuses[0].id); }