如何从angular 2中的组件向index.html传递值
发布时间:2020-12-17 17:28:14 所属栏目:安全 来源:网络整理
导读:我有一个angular2项目,其中index.html包含标题栏.其他组件将负责登录和显示其他内容. 我必须在标题栏中显示一个标识,仅当用户登录时才会出现在index.html中.如果用户登录,我在app.component.ts中设置一个标志.如何在index.html中引用该标志? body div class
我有一个angular2项目,其中index.html包含标题栏.其他组件将负责登录和显示其他内容.
我必须在标题栏中显示一个标识,仅当用户登录时才会出现在index.html中.如果用户登录,我在app.component.ts中设置一个标志.如何在index.html中引用该标志? <body> <div class="content-body"> <header class="header"> <div class="header-bar container"> <div class="header-bar__main"> <div class="header-heading"> <h1 class="page-title">noHold Application</h1> </div> </div> <a class="btn btn--small btn--icon ng-scope" title="Logout"><span class="icon-sign-out"></span></a> // this line should be displayed only if user logs in. </div> </header> <div class="content"> <div class="content__main"> <div class="container"> <app-root>Loading... </app-root> </div> </div> </div> </div> </body> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent { static loggedIn = false; getLoggedIn() { return AppComponent.loggedIn; } } 解决方法
在Angular中,最佳实践是拥有一个单独的引导组件(在许多情况下,以及在您的情况下为AppComponent),并定义其他组件(例如标题,菜单,页面内容,登录状态等).
在这种情况下,我建议您修改app.component.html,并使用自己的选择器介绍子组件.例如: app.component.html <header></header> <router-outlet></router-outlet> HeaderComponent的内容使用头标记/选择器呈现,而导航组件(例如:AboutComponent)的内容使用router-outlet标记/选择器呈现. header.component.ts import { Component } from '@angular/core'; @Component({ selector: 'header',templateUrl: './header.component.html',styleUrls: ['./header.component.css'] }) export class HeaderComponent { public loggedIn = false; ... } header.component.html <header class="header"> <div class="header-bar container"> <div class="header-bar__main"> <div class="header-heading"> <h1 class="page-title">noHold Application</h1> </div> </div> <div *ngIf="loggedIn"> <a class="btn btn--small btn--icon ng-scope" title="Logout"><span class="icon-sign-out"></span></a> </div> </div> </header> 希望它有用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |