我想在Angular 6中切换菜单

时间:2018-08-21 13:13:22

标签: angular angular-ui-router angular-routing

我要为自己切换侧面导航栏-

  
      
  1. 将布尔值toggle_menu设为true
  2.   
  3. 我在菜单栏中单击按钮时调用了函数togg()   设置布尔值false和af,因此切换了div
  4.   

但是问题是 有4个按钮,每个按钮都有其自己的div容器。每个按钮在单击togg()

时都会调用函数

所有div同时打开。

但是我想为每个按钮单击打开每个div

ts代码:

import { Component, OnInit } from '@angular/core';
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent{
   toggle_menu: boolean = true;
    constructor() { }
    togg() {
      return this.toggle_menu = !this.toggle_menu;
      }
  }

html代码:

<button class="dropdown-btn" (click)="togg();"> Besics</button>
        <div *ngIf="!toggle_menu">
        <a routerLink="/imp-style"> Implimenting Style  </a>
        </div>

<button class="dropdown-btn" (click)="togg();">Image</button>
        <div *ngIf="!toggle_menu">

        <a routerLink="/slider"> Image Slider</a>
        </div>
<button class="dropdown-btn" (click)="togg();">Forms</button>
        <div *ngIf="!toggle_menu">
        <a routerLink="/signup"> Signup </a>
        <a routerLink="/signup"> Login </a>
        <a routerLink="/signup"> Register </a>
        </div>
<button class="dropdown-btn" (click)="togg();">Service</button>
        <div *ngIf="!toggle_menu">
        <a routerLink="/dipika-task"> Data Display </a>
        <a routerLink="/social-media"> Social Media </a>
        <a routerLink="/student"> Student </a>
        </div>

5 个答案:

答案 0 :(得分:0)

现在,所有4个按钮的内部都有一个div,具体取决于.ts代码中的相同布尔值。

如果希望它们彼此独立地切换,并且每个按钮都切换其自己的滑块,则您的.ts代码中将需要有4个不同的布尔值。

这里是一个例子:

import pandas
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn import cross_validation
from sklearn.pipeline import Pipeline
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support as score
from sklearn.feature_extraction.text import TfidfVectorizer, HashingVectorizer, CountVectorizer, TfidfTransformer
from sklearn.metrics import precision_score, recall_score, confusion_matrix, classification_report, accuracy_score, f1_score

#csv file from train
df = pd.read_csv('data_train.csv', sep = ',')

#csv file from test
df_test = pd.read_csv('data_test.csv', sep = ',')

#Randomising the rows in the file
df = df.reindex(np.random.permutation(df.index))
df_test = df_test.reindex(np.random.permutation(df_test.index))

vect = CountVectorizer()

X = vect.fit_transform(df['data_train'])
y = df['label']

X_T = vect.fit_transform(df_test['data_test'])
y_t = df_test['label']

X_train, y_train = train_test_split(X, y, test_size = 0, random_state = 100)
X_test, y_test = train_test_split(X_T, y_t, test_size = 0, random_state = 100)

tf_transformer = TfidfTransformer(use_idf=False).fit(X) 
X_train_tf = tf_transformer.transform(X) 
X_train_tf.shape

tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X) 
X_train_tfidf.shape

tf_transformer = TfidfTransformer(use_idf=False).fit(X_T) 
X_train_tf_teste = tf_transformer.transform(X_T) 
X_train_tf_teste.shape

tfidf_transformer = TfidfTransformer()
X_train_tfidf_teste = tfidf_transformer.fit_transform(X_T) 
X_train_tfidf_teste.shape

#RegLog
clf = LogisticRegression().fit(X_train, y_train)

y_pred = clf.predict(X_test)

print("confusion matrix")
print(confusion_matrix(y_test, y_pred, labels = y))

print("F-score")
print(f1_score(y_test, y_pred, average=None))
print(precision_score(y_test, y_pred, average=None))
print(recall_score(y_test, y_pred, average=None)) 

print("cross validation")

scores = cross_validation.cross_val_score(clf, X, y, cv = 10)
print(scores)
print("Accuracy: {} +/- {}".format(scores.mean(), scores.std() * 2))

答案 1 :(得分:0)

export class AppComponent{
   dropdowns = {
    "besics": false,
    "images": false,
    "forms": false, 
    "service": false,
   }

    constructor() { }
    togg(string name) {
      dropwdowns[name] = !dropwdowns[name];
  }

在您的html中使用*ngIf

<button class="dropdown-btn" (click)="togg('besics');"> Besics</button>
        <div *ngIf="dropdowns['besics']">
        <a routerLink="/imp-style"> Implimenting Style  </a>
        </div>

<button class="dropdown-btn" (click)="togg('image');">Image</button>
        <div *ngIf="dropdowns['image']">
        <a routerLink="/slider"> Image Slider</a>
        </div>
<button class="dropdown-btn" (click)="togg('forms');">Forms</button>
        <div *ngIf="dropdowns['forms']">
        <a routerLink="/signup"> Signup </a>
             ....
        </div>
<button class="dropdown-btn" (click)="togg('service');">Service</button>
        <div *ngIf="dropdowns['service']">
        <a routerLink="/dipika-task"> Data Display </a>
             ....
</div>

答案 2 :(得分:0)

您需要为每个按钮维护不同的标志,以使其正常工作。

<button class="dropdown-btn" (click)="Besicstogg();"> Besics</button>
        <div *ngIf="!Besicstoggle_menu">
        <a routerLink="/imp-style"> Implimenting Style  </a>
        </div>

<button class="dropdown-btn" (click)="Imagetogg();">Image</button>
        <div *ngIf="!Imagetoggle_menu">

        <a routerLink="/slider"> Image Slider</a>
        </div>
<button class="dropdown-btn" (click)="Formstogg();">Forms</button>
        <div *ngIf="!Formstoggle_menu">
        <a routerLink="/signup"> Signup </a>
        <a routerLink="/signup"> Login </a>
        <a routerLink="/signup"> Register </a>
        </div>
<button class="dropdown-btn" (click)="Servicetogg();">Service</button>
        <div *ngIf="!Servicetoggle_menu">
        <a routerLink="/dipika-task"> Data Display </a>
        <a routerLink="/social-media"> Social Media </a>
        <a routerLink="/student"> Student </a>
         </div>

和ts文件中

 Servicetogg() {
      return this.Servicetoggle_menu = !this.Servicetoggle_menu;
  }
Besicstogg() {
      return this.Besicstoggle_menu = !this.Besicstoggle_menu;
  }
Imagetogg() {
      return this.Imagetoggle_menu = !this.Imagetoggle_menu;
  }
Formstogg() {
      return this.Formstoggle_menu = !this.Formstoggle_menu;
  }
Servicetogg() {
      return this.Servicetoggle_menu = !this.Servicetoggle_menu;
  }

答案 3 :(得分:0)

如何进一步简化它并消除冗余:

export interface MenuItem {
  title: string;
  links: { title: string, link: string }[]
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{

   menuItems: MenuItem [] = [
     { 
       title: 'Basics' ,
       links: {
         title: 'Implementing Style',
         link: '/imp-style'
       }
     },
     // ... put the rest here
   ];

   activeMenu?: MenuItem;

   toggle(menu: MenuItem): void {
     this.activeMenu = this.activeMenu === menu ? void 0 : menu;
   }

   isActive(menu: MenuItem): boolean {
     return this.activeMenu === menu;
   }
}

模板

<ng-container *ngFor="let menu of menuItems">
  <button class="dropdown-btn" (click)="toggle(menu)">{{menu.title}}</button>
  <div *ngIf="isActive(menu)">
    <a *ngFor="let link of menu.links" [routerLink]="link.link">{{link.title}}</a>
  </div>
</ng-container>

,如果您希望同时打开更多菜单:

activeMenus: MenuItem[] = [];

toggle(menu: MenuItem): void {
  if (this.isActive(menu)) {
    this.activeMenus.splice(this.activeMenus.indexOf(menu), 1);
  } else {
    this.activeMenu.push(menu);
  }
}

isActive(menu: MenuItem): boolean {
  return this.activeMenus.includes(menu);
}

答案 4 :(得分:0)

您只需在(click)函数中传递菜单名称并存储在变量中即可。

<li class="list-group-item" (click)="toggleMenu('menu')"> 
    <a href="javascript:void(0)" >Menu</a>
</li>

并在控制器中使用以下代码:

toggleMenu(menu: string): void{
    if(this.toggle == true && this.subsetting!='' && this.subsetting!=menu)
    this.toggle = false;

    this.subsetting  = menu;
    this.toggle = !this.toggle;
}

但首先在类中声明变量

toggle:boolean = false;
subsetting:string ='';