Angular *hasPermission指令的角度反应表单模型数据

Angular *hasPermission指令的角度反应表单模型数据,angular,typescript,angular-reactive-forms,Angular,Typescript,Angular Reactive Forms,我有一个反应式表单,它现在运行良好,但是我刚刚添加了一些与权限相关的复选框,通过这些复选框,我需要为创建的用户分配权限。共有3种类型的用户,他们可以拥有分配给他们的全部或选定权限。我不知何故也能从这些复选框中获取数据,但我需要以这样一种方式对数据进行建模,即权限必须包含在字符串数组中,*hasPermission指令才能工作。这是sampel所需的模型。Y= "skipTracing": { "permissions": ["view&quo

我有一个反应式表单,它现在运行良好,但是我刚刚添加了一些与权限相关的复选框,通过这些复选框,我需要为创建的用户分配权限。共有3种类型的用户,他们可以拥有分配给他们的全部或选定权限。我不知何故也能从这些复选框中获取数据,但我需要以这样一种方式对数据进行建模,即权限必须包含在字符串数组中,*hasPermission指令才能工作。这是sampel所需的模型。Y=

"skipTracing": {
  "permissions": ["view", "get"]
},
"affiliates": {
 "permissions": ["view"]
}
在建立正确的模型时,非常感谢您的帮助

但这就是它目前的工作方式

如果这里有很多代码,我很抱歉,但是在发布这个问题时从代码中删除选定的行似乎没有意义

这是我的.ts文件代码

export class AddMemberComponent extends AppBaseComponent implements OnInit {
  public activeRoute: string;
  private userId: string;
  private userData: Customer;
  public userDetailsForm: FormGroup;
  public permission = PERMISSIONS_LIST;
  public timeZoneList: TimeZone[] = TIMEZONE;
  public roles = [];
  public isFormLoaded = false;

  constructor(
    private inj: Injector,
    private route: ActivatedRoute,
    private teamService: TeamService
  ) {
    super(inj);
    this.route.url.subscribe((routeParams) => {
      this.activeRoute = routeParams[1].path;
      if (this.activeRoute === 'edit') {
        this.navigationState.breadCrums = [
          new BreadCrumb('Settings', USER_NAVIGATION_LINKS.settings),
          new BreadCrumb('Team', USER_NAVIGATION_LINKS.team),
          new BreadCrumb('Edit'),
        ];
      } else {
        this.navigationState.breadCrums = [
          new BreadCrumb('Settings', USER_NAVIGATION_LINKS.settings),
          new BreadCrumb('Team', USER_NAVIGATION_LINKS.team),
          new BreadCrumb('Add'),
        ];
      }
    });
    this.navigationService.updateNavigationState(this.navigationState);
  }

  /**
   * @ngdoc method
   * @description
   * A lifecycle hook that is called after Angular has
   * initialized all data-bound properties of a directive.
   * @returns void
   */
  public ngOnInit(): void {
    this.route.url.subscribe((routeParams) => {
      this.blockUI.startLoader();
      this.activeRoute = routeParams[1].path;
      if (this.activeRoute === 'edit') {
        this.route.paramMap.subscribe((params) => {
          this.userId = params.get('id');
          this.getUserDetails(this.userId);
        });
      } else {
        this.initForm();
        this.blockUI.stopLoader();
      }
    });
  }

  /**
   * @ngdoc method
   * @description
   * init from with validation
   */
  private initForm() {
    this.userDetailsForm = this.formBuilder.group(
      {
        memberFirstName: [
          '',
          ValidationUtil.requiredNonSpace,
          ValidationUtil.onlyAlphabets,
        ],
        memberLastName: [
          '',
          ValidationUtil.requiredNonSpace,
          ValidationUtil.onlyAlphabets,
        ],
        memberEmail: [
          '',
          [ValidationUtil.requiredNonSpace, ValidationUtil.validateEmail],
        ],
        memberMobileNumber: [
          '',
          [
            ValidationUtil.requiredNonSpace,
            Validators.minLength(10),
            Validators.maxLength(10),
          ],
        ],
        memberPassword: [''],
        memberConfirmPassword: [''],
        timezone: ['', ValidationUtil.requiredNonSpace],
        randomPassword: [true],
        sendEmail: [true],
        isActive: [true],
        selectAll: [false],
        skipTracing: this.initPermissions(
          this.permission.skipTracing,
          'skipTracing'
        ),
        affiliates: this.initPermissions(
          this.permission.affiliates,
          'affiliates'
        ),
        integrations: this.initPermissions(
          this.permission.integrations,
          'integrations'
        ),
      },
      {
        validator: ValidationUtil.MustMatch(
          'memberPassword',
          'memberConfirmPassword'
        ),
      }
    );

    if (this.activeRoute === 'edit') {
      this.prepareFormWithData();
    }

    this.isFormLoaded = true;
  }

  /**
   * @ngdoc method
   * @description
   * select or deselect all permission
   * on select all checkbox clicked
   */
  public onSelectAllClicked() {
    const checkValue: boolean = this.userDetailsForm.controls.selectAll.value;
    this.togglePermissionCheckboxes('skipTracing', checkValue);

    this.togglePermissionCheckboxes('affiliates', checkValue);
    this.togglePermissionCheckboxes('integrations', checkValue);
  }

  private togglePermissionCheckboxes(type: string, value: boolean) {
    const that = this;
    this.permission[type].forEach((permission, i) => {
      console.log(permission);
      console.log(this.permission[type][i]);
      let permissionData = { permissions: [] };
      if (this.permission[type]) {
        permissionData.permissions.push(permission.value);
        const group: FormGroup = that.userDetailsForm.controls[
          type
        ] as FormGroup;
        console.log(group.value);
        group.controls[type + i].setValue(permissionData);
      }
      console.log('Permission Data', permissionData);
    });
  }
}
HTML代码

<div class="ml-4 add-member-form">
    <div class="col-md-12 col-lg-9 col-sm-12 bg-white px-4 pb-5">
        <form [formGroup]="userDetailsForm" #ngForm="ngForm" appDebounceSubmit (debounceSubmit)="submit()" *ngIf="isFormLoaded">
            <a class="bst-blue-btn m-3 float-right p-1 icon-color" *ngIf="activeRoute === 'edit'"><img src="assets/images/edit-icon.svg" alt="" /></a>
            <div class="row">
                <div class="col-md-5 form-group">
                    <label>First name</label>
                    <input type="text" class="form-control" formControlName="memberFirstName" placeholder="Type First Name">
                    <bfv-messages></bfv-messages>
                </div>
                <div class="col-md-6 form-group">
                    <label>Last name</label>
                    <input type="text" class="form-control" formControlName="memberLastName" placeholder="Type Last Name">
                    <bfv-messages></bfv-messages>
                </div>
            </div>
            <div class="row">
                <div class="col-md-3 form-group">
                    <label>Email</label>
                    <input type="text" class="form-control" formControlName="memberEmail" placeholder="Type Email"
                        [readonly]="activeRoute === 'edit'">
                    <bfv-messages></bfv-messages>
                </div>
                <div class="col-md-3 form-group">
                    <label>Mobile phone</label>
                    <input type="text" class="form-control" formControlName="memberMobileNumber" placeholder="Type Mobile number"
                        mask='000-000-0000'>
                </div>
                <div class="col-md-4 form-group">
                    <label> Timezone</label>
                    <select class="form-control" formControlName="timezone">
                        <option value="">Choose your Timezone</option>
                        <option *ngFor="let tZone of timeZoneList" [ngValue]="tZone.value">{{tZone.zone}}
                        </option>
                    </select>
                    <bfv-messages></bfv-messages>
                </div>
            </div>
            <div class="row" *ngIf="!getFormControl('randomPassword').value">
                <div class="col-md-3 form-group">
                    <label>Password</label>
                    <input type="password" class="form-control" formControlName="memberPassword" placeholder="Type Password">
                    <bfv-messages></bfv-messages>
                </div>
                <div class="col-md-3 form-group">
                    <label>Confirm Password</label>
                    <input type="password" class="form-control" formControlName="memberConfirmPassword"
                        placeholder="Type Confirm Password">
                    <bfv-messages></bfv-messages>
                </div>
            </div>
            <div class="custom-checkbox mt-2">
                <label class="mr-2 radio-cstm" *ngIf="activeRoute !== 'edit'"> Set random password 
                    <input type="checkbox" formControlName="randomPassword" (change)="onRandomPasswordChanged()" />
                    <span class="checkmark"></span>
                </label>
                <label class="mr-2 radio-cstm" *ngIf="activeRoute !== 'edit'"> Send activation email 
                    <input type="checkbox" formControlName="sendEmail" />
                    <span class="checkmark"></span>
                </label>
                <label class="radio-cstm"> Mark as active 
                    <input type="checkbox" formControlName="isActive" />
                    <span class="checkmark"></span>
                </label>
            </div>
            <div class="custom-checkbox">
                <h5 class="font-weight-bold mt-4">PERMISSIONS</h5>
            </div>
            <div class="custom-checkbox mt-4">
                <div class="row">
                    <div class="col-md-6 col-lg-3">
                        <label class="radio-cstm">Select All
                            <input type="checkbox" formControlName="selectAll" (change)="onSelectAllClicked()" />
                            <span class="checkmark"></span>
                        </label></div>
    
                    <div class="col-md-6 col-lg-3" [formGroup]="userDetailsForm.controls.skipTracing">
                        <h6 class="chekListHd">SKIP TRACING</h6>
                        <label *ngFor="let permission of permission.skipTracing; let i=index;" class="radio-cstm">
                            {{permission.name}}
                            <input type="checkbox" formControlName="skipTracing{{i}}" />
                            <span class="checkmark"></span>
                        </label>
                    </div>
                    <div class="col-md-6 col-lg-3" [formGroup]="userDetailsForm.controls.integrations">
                        <h6 class="chekListHd">INTEGRATIONS</h6>
                        <label *ngFor="let integration of permission.integrations; let i=index;" class="radio-cstm">
                            {{integration.name}}
                            <input type="checkbox" formControlName="integrations{{i}}" />
                            <span class="checkmark"></span>
                        </label>
                    </div>
                    <div class="col-md-6 col-lg-3" [formGroup]="userDetailsForm.controls.affiliates">
                        <h6 class="chekListHd">AFFILIATES</h6>
                        <label *ngFor="let affiliate of permission.affiliates; let i=index;" class="radio-cstm">
                            {{affiliate.name}}
                            <input type="checkbox" formControlName="affiliates{{i}}" />
                            <span class="checkmark"></span>
                        </label>
                    </div>
                </div>
            </div>
            <div class="col-md-6 d-flex mt-5">
                <app-bst-button isSubmit="true" btnClass="btn-img mr-3">
                    <img src="../../../../../assets/images/save.svg" alt="" class="mr-3">
                    SAVE USER
                </app-bst-button>
                <app-bst-button btnClass="btn bst-white-btn btn-img" routerLink="/app/settings/team">
                    <span class="close-icon mr-3">×</span> CANCEL
                </app-bst-button>
            </div>
        </form>
    </div>
</div>
import { Permissions, PermissionType } from '../models/customer.model';

const SKIPTRACING = [
  new PermissionType('Place Orders', 'place-orders'),
  new PermissionType('View Past Orders', 'view-past-orders'),
];

const AFFILIATES = [new PermissionType('View Affiliates', 'view-affiliates')];

const INTEGRATIONS = [
  new PermissionType('Access Integrations', 'access-integrations'),
];
export const PERMISSIONS_LIST = new Permissions(
  SKIPTRACING,
  AFFILIATES,
  INTEGRATIONS
);