【问题标题】:Angular reuse of property from component to component从组件到组件的角度重用属性
【发布时间】:2018-10-09 16:56:11
【问题描述】:

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

在 Angular 5 中,您将如何在组件之间重用属性(此处为标题)? 假设我在app.component.ts 中定义了属性title,我希望最终在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...';
}

login.component.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 -->

您能否建议如何处理?

【问题讨论】:

    标签: angular components angular5


    【解决方案1】:

    您可以通过@Input() / @Output() 或通过共享的Service 在Angular wither 中传递数据。

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

    如果您更深入地传递数据,建议使用

    Service。在您的情况下,您似乎将其传递得更深。所以你要做的是创建一个新的custom-service.service.ts 文件,将它添加到app.module.ts 中的providers 数组中(这样它就变成了整个应用程序的单例),将此服务注入到所有通信的组件中。存储服务中的属性 - 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 2021-03-25
      • 2019-10-15
      • 2023-04-09
      • 2021-08-11
      • 1970-01-01
      相关资源
      最近更新 更多