如何防止角料mat-menu关闭?

时间:2017-10-27 05:17:35

标签: javascript angular angular-material2

我正在角度材质中创建一个日期时间选择器控件,并使用以下代码来执行该操作

<button mat-button [matMenuTriggerFor]="menu">
    <mat-icon>date_range</mat-icon>
    <span>Date Range</span>
</button>
<mat-menu #menu="matMenu">
    <div fxLayout="row">
        <div fxLayout="column">
            <button (click)="setInterval(15)" mat-menu-item>Last 15 minutes</button>
            <button (click)="setInterval(360)" mat-menu-item>Last 6 hours</button>
            <button (click)="setInterval(1440)" mat-menu-item>Last 24 hours</button>
            <button (click)="setInterval(2880)" mat-menu-item>Last 2 days</button>
            <button (click)="setInterval(10080)" mat-menu-item>Last 7 days</button>
            <button (click)="setInterval(-1)" [matMenuTriggerFor]="dateTimeMenu" mat-menu-item>Custom</button>
        </div>
        <mat-menu class="date-range-menu" #dateTimeMenu="matMenu">
            <div fxLayout="row">
                <div fxLayout="column">
                    <b>From</b>
                    <mat-calendar></mat-calendar>
                </div>
                <div fxLayout="column">
                    <b>To</b>
                    <mat-calendar></mat-calendar>
                </div>
            </div>
        </mat-menu>
    </div>
</mat-menu>

目前,当我点击某个按钮时,它正在关闭菜单。我知道我们可以在每个mat-menu-item上执行$ event.stoppropagation()以防止它关闭。

但我想知道是否有可能为mat-calendar

做到这一点

enter image description here

正如您在上面的图像中看到的那样,当我选择日期时,它正在关闭菜单。是否有可能阻止这种情况?

6 个答案:

答案 0 :(得分:32)

您只需将 import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.pipeline import Pipeline from nltk import word_tokenize from textblob import TextBlob cov = pd.read_csv("F:/kipro/ml/dataset.csv", names = ["Complaint", "target"]) cov.dropna() s=pd.factorize(cov['target']) cov['tarname']=s[0] msk = np.random.rand(len(cov)) < 0.8 train = cov[msk] test = cov[~msk] train.dropna() test.dropna() y_train, y_test = train.tarname, test.tarname def tokens(message): return TextBlob(message).words def lemmas(message): message=message.lower() words = TextBlob(message).words return [word.lemma for word in words] text_clf = Pipeline([('vect', CountVectorizer(analyzer=lemmas)), ('tfidf', TfidfTransformer()), ('clf-svm', SGDClassifier()) ,]) text_clf = text_clf.fit(train['Complaint'].values.astype('U'),train['tarname']) predicted = text_clf.predict(test['Complaint'].values.astype('U')) x=np.mean(( y_test==predicted))*100 print(x) 添加到这些日历的父元素即可。如下所示,

(click) = "$event.stopPropagation()"

Stackblitz demo

答案 1 :(得分:2)

如果您甚至想停止关闭mat-menu,即使单击了mat-menu-content,我也确实在锚标签而不是mat-menu上添加了$event.stopPropogation()。 因此,即使在表单上的任何位置单击,菜单栏也不会关闭。

Example:- 
    <mat-menu #nameAndDescriptioContextMenu="matMenu" [hasBackdrop]="false">
         <a (click)="$event.stopPropagation();$event.preventDefault();">
               <div>
                 Form Group Form
               </div> 
         </a> 
    </mat-menu>

答案 2 :(得分:1)

通过返回上一个解决方案,将指令封装在方法中可避免关闭菜单并继续执行指令

在HTML中:

<mat-menu class="date-range-menu" #dateTimeMenu="matMenu">
    <div fxLayout="row">
        <div fxLayout="column" (click)="doSomething($event);">
            <b>From</b>
            <mat-calendar></mat-calendar>
        </div>
        <div fxLayout="column" (click)="doSomething($event)">
            <b>To</b>
            <mat-calendar></mat-calendar>
        </div>
    </div>
</mat-menu>

在TS中:

doSomething($event:any){
    $event.stopPropagation();
    //Another instructions
}

答案 3 :(得分:1)

不幸的是,以上答案对我都不起作用。如果您需要菜单面板比内容宽得多,则无法放置"$event.stopPropagation();",因此,如果单击mat-menu-panel,它将关闭。 幸运的是,仍然可以通过“重写” MatMenu的click事件来避免这种情况。 感谢同事:https://stackblitz.com/edit/mat-menu-disable-close

ngAfterViewInit() {
    // Inject our custom logic of menu close
    (this.searchMenu as any).closed = this.searchMenu.close = this.configureMenuClose(this.searchMenu.close);
  }

private configureMenuClose(old: MatMenu['close']): MatMenu['close'] {
    const upd = new EventEmitter();
    feed(upd.pipe(
      filter(event => {
        if (event === 'click') {
          // Ignore clicks inside the menu 
          return false;
        }
        return true;
      }),
    ), old);
    return upd;
  }
}
function feed<T>(from: Observable<T>, to: Subject<T>): Subscription {
  return from.subscribe(
    data => to.next(data),
    err => to.error(err),
    () => to.complete(),
  );
}

这样,只有在您单击外部(这很容易删除)并且使用触发器时,它才会关闭。 这就是我在项目中想要的行为,希望对某人有用。

答案 4 :(得分:1)

您有很多选择,我邀请您尝试以下

    <mat-menu [hasBackdrop]="false">
     <div  (click)="$event.stopPropagation()" (keydown)="$event.stopPropagation()">
     ...
     </div>
    </mat-menu>

[hasBackdrop] =“ false” ,如果您想防止在单击框外的任何位置时关闭菜单,否则将其删除

答案 5 :(得分:0)

您可以直接在组件中使用此指令。

HTML

<mat-menu class="date-range-menu" #dateTimeMenu="matMenu">
    <div fxLayout="row">
        <div fxLayout="column" mat-filter-item>
            <b>From</b>
            <mat-calendar></mat-calendar>
        </div>
        <div fxLayout="column" mat-filter-item >
            <b>To</b>
            <mat-calendar></mat-calendar>
        </div>
    </div>
</mat-menu>

将其另存为filter.directive.ts 从“ @ angular / core”导入{指令,HostListener,HostBinding};

@Directive({
  selector: "[mat-filter-item]"
})
export class FilterItemDirective {
  @HostListener("click", ["$event"])
  onClick(e: MouseEvent) {
    e.stopPropagation();
    e.preventDefault();

    return false;
  }
}