typescript 如何将值从 angular 2 中的组件传递给 index.html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42924373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:21:52  来源:igfitidea点击:

How to pass a value to index.html from component in angular 2

angulartypescript

提问by Santosh Hegde

I have an angular2 project where index.htmlcontains header bar. Other components will take care of logging in and displaying other stuff.

我有一个 angular2 项目,其中index.html包含标题栏。其他组件将负责登录和显示其他内容。

I have to show a logo in header bar which is present in index.htmlonly if the user loggedIn. I'm setting a flag in app.component.tsif the user logged in. How to refer that flag in 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

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;
  }

}

采纳答案by Burak Tasci

In Angular, it's a best practiceto have one singlebootstrap component (AppComponentin many cases, as well as in your case), and define other components (such as header, menu's, page content, login status, etc).

在 Angular 中,最佳实践是拥有一个引导程序组件(AppComponent在许多情况下,以及在您的情况下),并定义其他组件(例如标题、菜单、页面内容、登录状态等)。

In this case, I suggest you to modify your app.component.html, and introduce child components using their own selectors. For instance:

在这种情况下,我建议您修改您的app.component.html, 并使用自己的选择器引入子组件。例如:

app.component.html

应用程序组件.html

<header></header>
<router-outlet></router-outlet>

Contents of HeaderComponentare rendered using the headertag/selector whereas contents of navigated components (ex: AboutComponent) are rendered using the router-outlettag/selector.

的内容HeaderComponent使用header标签/选择器呈现,而导航组件(例如:)的内容AboutComponent使用router-outlet标签/选择器呈现。

header.component.ts

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

头文件.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>

Hope it's helpful.

希望它有帮助。

回答by gentiane

Take care to not couple your components. A component should not access properties of another component. There is many ways to decouple components. In your case a good choice could be to share common data between components.

注意不要耦合您的组件。一个组件不应访问另一个组件的属性。有很多方法可以解耦组件。在您的情况下,一个不错的选择可能是在组件之间共享公共数据。

Here is a quick example of implementation. Create a class that represents your user :

这是一个实现的快速示例。创建一个代表您的用户的类:

class User {
  firstName: string;
  lastName: string;
  ...
}

Create a class that contains your user's session state :

创建一个包含用户会话状态的类:

class Session {
  user: User;
  isLogged: boolean;

  login(user: User) {
    this.user = user;
    this.isLogged = true;
  }
}

Then your configure your application module to inject an instance of the Session class as a singleton :

然后配置应用程序模块以将 Session 类的实例作为单例注入:

@NgModule({
  ...
  providers: [
    ...
    { provide: 'session', useValue: new Session() },
    ...
  ],
  ...
})

Now in all your components, your can inject your session. An exemple in the login component that sets the user when he authenticates :

现在在你的所有组件中,你可以注入你的会话。登录组件中设置用户身份验证时的示例:

@Component({
  ...
})
class LoginComponent {
  constructor(private session: Session) {
  }

  private login() {
    let user = ....;  // Retrieve user from backend service...
    this.session.login(user);
  }
}

And you can also use the session in your templates :

您还可以在模板中使用会话:

<div *ngIf="session.isLogged">
  <a class="btn btn--small btn--icon ng-scope" title="Logout"><span class="icon-sign-out"></span></a>
</div>