当我使用Angular2点击div时,如何让它显示出来



下面是我显示/隐藏ul列表的临时独奏,但我想用Angular 2来完成它。

//这是应用程序组件.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>

这很简单-只需在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>

您可以在用户列表div.y中使用*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>

最新更新