以下是我显示/隐藏ul-list的临时性,但我想用Angular 2完成它。
//这是 app.component.ts
@component({
templateUrl: 'app/app.component.html',
providers: [UserService]
})
export class AppComponent implements OnInit {
UserLists: UserList[];
showhide(id: string){
var e=document.getElementById(id);
e.style.display = (e.style.display == 'block') ? 'none' : 'block';
}
}
//这是 user.service.ts
export class UserList{
name: string;
link: string;
}
@Injectable()
export class UserService{
UserLists: UserList[] = AdminList;
}
export var AdminList: UserList[]=[{
name: "a",
link: ""
},{
name: "b",
link: ""
}]
以下是 app.component.html
<div class="user">welcome<a class="user-name" (click)="showhide('user-list')"><span>admin<img src="a.png"></span></a>
<div id="user-list" class="user-list" style="display: none;">
<ul>
<li *ngFor="let list of UserLists">
<a [routerLink]="[list.link]" routerLinkActive="active">{{list.name}}</a>
</li>
</ul>
</div>
</div>
答案 0 :(得分:0)
这非常简单 - 只需将成员变量添加到AppComponent
:
@component({
templateUrl: 'app/app.component.html',
providers: [UserService]
})
export class AppComponent implements OnInit {
UserLists: UserList[];
showUserList: boolean = true; // <-- member variable to hold status
}
在您的HTML模板中,您可以点击并点击*ngIf
来显示/隐藏它:
<div class="user">welcome<a class="user-name" (click)="showUserList = !showUserList"><span>admin<img src="a.png"></span></a>
<div id="user-list" class="user-list" *ngIf="showUserList">
<ul>
<li *ngFor="let list of UserLists">
<a [routerLink]="[list.link]" routerLinkActive="active">{{list.name}}</a>
</li>
</ul>
</div>
</div>
答案 1 :(得分:0)
您可以在用户列表div中使用* ngIf或[hidden]。是或者可能不需要showhide方法。像这样: -
在你的HTML中
<div class="user">welcome<a class="user-name" (click)="showList = !showList"><span>admin<img src="a.png"></span></a>
<div id="user-list" class="user-list" *ngIf="showList">
<ul>
<li *ngFor="let list of UserLists">
<a [routerLink]="[list.link]" routerLinkActive="active">{{list.name}}</a>
</li>
</ul>
</div>