简体   繁体   English

angular4材质表

[英]angular4 material table

 @Component({ selector: "app-dynamic-table", template: ` ` }) export class DynamicTableComponent { private _columns = [ { name: "date", show: true }, { name: "selected", show: true }, { name: "id", show: true }, { name: "location3", show: false }, { name: "location4", show: false }, { name: "location5", show: false } ]; get columns() { return this._columns; } get displayedColumns(): string[] { return this._columns.map(c => c.name); } } 

the above code successfully able to hide and show the material table column,But I need to restrict the user to select less than 3 column of table and should show the alert message.Could you anyone look inti that? 上面的代码可以成功隐藏和显示物料表列,但是我需要限制用户选择表的少于3列,并且应该显示警报消息。任何人都可以看到吗?

You can keep click event on your checkbox , and check the limit of checkbox selection on that event and decide whether to proceed with the event or not. 您可以将click event保留在您的checkbox ,并检查该事件上checkbox选择的限制,并决定是否继续该事件。 If you prevent that event to happen, then eventually it will not fire change event of checkbox 如果您prevent该事件的发生,那么最终它不会触发checkbox change事件

Code

checkLimit(event) {
    // To make this SSR proof code, you could consider using Renderer to query DOM
    let dom = event.currentTarget.querySelector('.mat-checkbox-input');
    console.dir('Dom', dom, event.currentTarget)
    if (!dom.checked && this.columns.filter(col => col.show).length >= 3) {
      event.stopPropagation()
      event.preventDefault()
      alert('Cant select more than three column')
      return
    }
}

Html HTML

<mat-checkbox *ngFor="let column of columns" 
  (click)="checkLimit($event)"
  [(ngModel)]="column.show">
    {{column.name | titlecase}}
</mat-checkbox>

Really appreciate Pankaj Answer. 非常感谢Pankaj回答。 But it's not an angular way. 但这不是一个有角度的方法。 Accessing DOM in component and checking without renderer2. 在组件中访问DOM并在没有renderer2的情况下进行检查。 Here is the angular way of achieving the same solution. 这是实现相同解决方案的角度方法。

Component: 零件:

validate(index, column, event){
    column.show = !column.show;
    const matches = this.columns.filter(item=> item.show);
    if(matches.length >= 3){
      alert('not allowed');
      event.stopPropagation();
      event.preventDefault();
      column.show = false;
    }
  }

Template : 范本:

<div *ngFor="let column of columns; let i=index;">
  <input type="checkbox" id="{{i}}" name="feature{{i}}"
    value="{{column.name}}"   [checked]="column.show" ([ngModel])="column.show" (click)="validate(i, column, $event)">
    <label for="feature{{i}}">{{column.name}}</label></div>

https://stackblitz.com/edit/angular-q2wrc4 https://stackblitz.com/edit/angular-q2wrc4

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM