简体   繁体   English

Angular - 如何选中和取消选中所有用户角色

[英]Angular - How to Check and Uncheck All User Roles

I am currently working on a web portal with Angular-7 as frontend and Laravel-5.8 as backend.我目前正在开发一个 web 门户,其中 Angular-7 作为前端,Laravel-5.8 作为后端。 Also, I use Laravel Spatie for User Role Management.另外,我使用 Laravel Spatie 进行用户角色管理。

user.component.ts用户.component.ts

export class UsersComponent implements OnInit {

  users = null;     //Store Users Data
  roles = null;     //Store all roles Data
  clients = null;

  public error = {
    'role' : null,
    'email' : null,
    'client_id' : null,
    'first_name' : null,
    'last_name' : null,
    'password' : null
  };
       //Form errors
  keyword = null;   //Current Search Keyword
  pagination = {    //Current Pagination data
    'page' :  '1',
    'max' : '10'
  }
  role = null;
  User = 'User';

  data = {          //User Update Data
    "id" : null,
    "first_name" : null,
    "last_name" : null,
    "client_id" : null,
    "role" : []
  }

  form = {         //New User add Data
    'first_name' : null,
    'last_name' : null,
    'email' : null,
    'client_id' : null,
    'password' : null,
    'password_confirmation' : null,
    'role' : []
  }

  headers = {     //Token for API Authorization
    'Authorization' : this.token.get(),
    'X-Requested-With' : 'XMLHttpRequest'
  }

  sortData = {        //Current Sort Data
    "col" : null,
    "order" : null
  }

  isSuperAdmin = false;

  constructor(private roleManage : RolesCheckService , private route : ActivatedRoute, private pg: NgbPaginationConfig, private token : TokenService, private http : HttpClient, private router : Router,private api : ApiService, private notify : SnotifyService) {
    pg.boundaryLinks = true;
    pg.rotate = true;
  }

  ngOnInit() {

    console.log('isSuperAdmin: ' + this.roleManage.isSuperAdmin);
    this.isSuperAdmin = this.roleManage.isSuperAdmin;
    this.route.queryParams.subscribe(params => {
      if(params['role']){
        this.role = params['role'];
        this.User = this.role;

      } else {
        this.User = 'User';
        this.role = '';
      }
    })
  }

  checkboxAdd(event){
    if(event.srcElement.checked){
      this.form.role.push(event.srcElement.name);
    } else {
      var index =this.form.role.indexOf(event.srcElement.name);
      this.form.role.splice(index, index+1);
    }
    console.log(this.form.role);
  }

}

user.component.html user.component.html

<div id="addModal" class="modal" style="background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4);">

      <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">Add New {{ User }}</h5>
              <button type="button" class="close" (click)='closeAddModal()'>
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
              <form #editUserForm=ngForm>

                  <div class="form-group">
                    <label for="name">First Name</label>
                    <input type="name" name="first_name" id="inputName" class="form-control" placeholder="First Name" [(ngModel)]="form.first_name" required>
                  </div>
                  <div class="form-group">
                      <label for="name">Last Name</label>
                      <input type="name" name="last_name" id="inputName" class="form-control" placeholder="Last Name" [(ngModel)]="form.last_name" required>
                    </div>
                  <div class="form-group">
                      <label for="name">Email</label>
                      <input type="email" name="email" id="inputEmail" class="form-control" placeholder="example@email.com" required [(ngModel)]="form.email">
                  </div>
                    <div class="form-group">
                        <label for="name">Role</label>
                        <div *ngFor="let role of roles">
                            <input type="checkbox" name="{{ role.name }}" value="{{ role.name }}" (change)="checkboxAdd($event)"> {{ role.name }}
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="name">Password</label>
                  <input type="password" name="password" id="inputPassword" [(ngModel)]="form.password" class="form-control" placeholder="Password" required>
                </div>

                <div class="form-group">
                    <label for="name">Password Confirmation</label>
                  <input type="password" name="password_confirmation" id="inputPasswordConfirm" [(ngModel)]="form.password_confirmation" class="form-control" placeholder="Re enter Password" required>
                </div>
              </form>

            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary" (click)='addModalSubmit()' [disabled]="!editUserForm.valid">Save changes</button>
              <button type="button" class="btn btn-secondary" (click)='closeAddModal()'>Close</button>
            </div>
          </div>
        </div>
  </div>

Currently, I use目前,我使用

checkboxAdd(event)复选框添加(事件)

to select the User Role-Permission one-by-one. select User Role-Permission 一一对应。 But I want to be able to Select/Unselect All at once as shown below:但我希望能够一次全选/取消全选,如下所示:

全选

How do I achieve this?我如何实现这一目标?

Try using Angular reactive forms instead.尝试使用 Angular 反应式 forms 代替。 They make it much easier to bind actions to data changes.它们使将操作绑定到数据更改变得更加容易。

private form: FormGroup = this.fb.group({
  selectAll: false,
  user: this.fb.group({
    roles: this.fb.array([])
  })
});
constructor(private fb: FormBuilder){}


ngOnInit(){
  this.form.get('selectAll').valueChanges.subscribe(selectAll => {
    const roles = this.form.get('user.roles');

   // Remove all roles first
    while(roles.value.length > 0){
      roles.removeAt(0);
    }

    if(selectAll){
      // Add all roles
      this.roles.forEach(role => {
        roles.push(this.fb.control(role.name));
      });

      return;
    }
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何选中和取消选中 angular 7 中的所有复选框 - How to Check and Uncheck all checkbox in angular 7 Angular - 选中/取消选中所有复选框 - Angular - Check/Uncheck All Checkboxes 如何取消选中 Angular 中 forloop 中的特定复选框 - How to uncheck the particular check box in forloop in Angular 角度:HTML表格句柄选中/取消选中/全部选中 - Angular: HTML Table handle check/uncheck/check all AG-GRID-ANGULAR - 如果选中/取消选中单元格渲染器中的所有复选框,如何选中/取消选中标题组件中的复选框? - AG-GRID-ANGULAR - How to check/uncheck checkbox in header component if all checkboxes in the cell renderers are checked/unchecked? 在 ASP.NET Core 3 (3.0) SPA (Angular) 中如何正确检查用户角色? - In ASP.NET Core 3 (3.0) SPA (Angular) how to properly check for user roles? 如何使用angular2获取选中和取消选中的值 - How to get the values on check and uncheck using angular2 如何根据API响应检查和取消选中mat-checkbox:Angular 6 - How to check and uncheck mat-checkbox based on API response : Angular 6 如何基于angular2中复选框的选中和取消选中给出下拉值 - How to give dropdown values based on check and uncheck of checkbox in angular2 如何以编程方式选中或取消选中 Angular 8 的复选框? - How do I programmatically check or uncheck my checkbox with Angular 8?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM