ngModel 在表单标签中不起作用

har*_*mar 2 multi-select angularjs-directive angular-material angular

[(ngModel)] 不能在表单标签内工作

当我使用 Multi Select Outside Form 标签时,可以正常选择 All 和 Deselect All 功能

但是我当我把它放在表格里面时它工作选择所有值

<form [formGroup]="roleForm">

    <mat-form-field class="example-full-width">
        <mat-select placeholder="Select Role Type" formControlName="roleType" (selectionChange)="roleTypeSelect($event.value)">
            <mat-option *ngFor="let role of roleTypeList" [value]="role.roleTypeId">
                {{role.roleTypeName}}
            </mat-option>
        </mat-select>
    </mat-form-field> <!-- Multi Select Mat Start -->
    <mat-form-field class="example-full-width">

        <mat-select placeholder="Select Privileges" class="filter-select" [formControl]="selectedItems" [compareWith]="equals" multiple
         #privilegeSelect="ngModel">
            <mat-option disabled="disabled" class="filter-option">
                <button mat-raised-button class="mat-primary fill text-sm" (click)="selectAll(privilegeSelect, dropdownList)">
                    Select All
                </button>
                <button mat-raised-button class="mat-primary fill text-sm eta-margin-all" (click)="deselectAll(privilegeSelect)">
                    Deselect All
                </button>
            </mat-option>
            <mat-option *ngFor="let privilege of dropdownList" [value]="privilege">{{privilege.itemName}}</mat-option>
        </mat-select>

    </mat-form-field>
    <!-- Multi select mat end -->

</form>
Run Code Online (Sandbox Code Playgroud)

bvd*_*vdb 5

如果您只是在ngModel没有周围的情况下使用<form>,则不必name为输入指定 a 。

<input ... [(ngModel)]="model.something"`>
Run Code Online (Sandbox Code Playgroud)

但是当你在表单中使用它时,该name属性就变成了强制性的!

<form>
  <input ... name="something" [(ngModel)]="model.something"`>
</form>
Run Code Online (Sandbox Code Playgroud)

它实际上在文档中:

在标签中使用 ngModel 时,您还需要提供一个 name 属性,以便控件可以在该名称下向父表单注册。

如果你错过了它,它根本不会显示任何错误,它只是不起作用。