首页 > 解决方案 > 从组件到组件的角度重用属性

问题描述

我从 Angular 开始,完成了教程,试图掌握概念,但我遇到了一个看似简单的问题。试图用谷歌搜索,但我无法解决这个问题。

在 Angular 5 中,您将如何在组件之间重用属性(此处为标题)?假设我title定义了app.component.ts我希望最终在login.compoment.html??中重用的属性

app.module.ts

@NgModule({
  imports: [
    AppRoutingModule
  ],

  declarations: [
    AppComponent,
    LoginComponent,
  ],

  providers:[
    // services
  ],

  bootstrap: [AppComponent]
})

export class AppModule {}

app.component.ts

@Component({
  selector : 'app-root',
  template : `<router-outlet></router-outlet>`
})

export class AppComponent {
    title = 'A global title...';
}

登录组件.ts

@Component({
    selector   : 's-login-pg',
    templateUrl: './login.component.html',
    styleUrls  : [ './login.scss'],
})
export class LoginComponent implements OnInit {
    // should title be referenced here? 
    // should the AppComponent be imported again, as they are already both defined in app module ?
}

login.component.html

<div>{{title}}</div> <!-- I want the title in app.component.ts to show up -->

你能建议如何处理这个问题吗?

标签: angularcomponentsangular5

解决方案


@Input()您可以通过/@Output()或通过共享的 Angular 凋零传递数据Service

如果您将数据从父组件传递到子组件,则建议使用@Inout / @Output (尽管您可以以相同的方式将其更深地发送)。

如果您更深入地传递数据,建议使用服务。在您的情况下,您似乎将其传递得更深。所以你要做的是创建一个新custom-service.service.ts文件,将其添加到 providers 数组中app.module.ts(因此它成为整个应用程序的单例),将此服务注入到所有通信的组件中。存储服务中的属性 - title: string

app.component.ts您注入此服务时:

import {CustomService} from '...path'

title = 'My title';
constructor(private custService: CustomService) {
}

ngOnInit() {
  this.custService.title = this.title;
}

现在每个导入该服务的组件都可以访问它的title属性并获得它的值:

import {CustomService} from '...path'

title: string;
constructor(private custService: CustomService) {
}

ngOnInit() {
  this.title = this.custService.title;
}

推荐阅读