【问题标题】:Access constant in child component from Parent component从父组件访问子组件中的常量
【发布时间】:2018-06-13 21:25:47
【问题描述】:

我有两个组件,我想在点击时从父组件打印子组件中的文本。

父组件:

import {Component, OnInit, ViewChild} from '@angular/core';

@Component({
selector: 'parent',
templateUrl: 'parent.html'
})
export class ParentComponent implements OnInit {
   @ViewChild(ChildComponent) child;

   constructor() {
   }

   ngOnInit() {
   }

   click(){
       console.log(this.child.text);
   }
}

子组件:

import {Component, OnInit} from '@angular/core';

@Component({
selector: 'child',
templateUrl: 'child.html'
})
export class ChildComponent implements OnInit {

   constructor() {
   }

   ngOnInit() {
       const text = 'TEXT HERE';
   }

   //Some code...
}

我是 Angular 的新手。只是想知道如何使它工作,我希望一些常量在一个点上并由其他人共享。常量不必仅在子组件中。只需要一个关于如何使其与良好的编码策略一起工作的好建议

这对我不起作用。

谢谢

【问题讨论】:

标签: angular typescript


【解决方案1】:

我的解决方案是在这两个组件之间创建一个 sharedService

/// SharedService


export class SharedService {
   sharedConst: string = 'blabla';
}


//// ParentComponent


@Component({
    ...,
    providers: [SharedService]
})

export class ParentComponent {
    constructor(private sharedService: SharedService){}
}

//// ChildComponent

@Component({
    ...,
    template: `{{sharedService.sharedConst}}`
})

export class ChildComponent {


   constructor(public sharedService: SharedService){}
}

【讨论】:

  • 这是一个很好的解决方案,但只是想知道在我的情况下这是否是一个好主意。在我的大型应用程序中,我只有 3 个常量字符串,我只想与两个组件共享。就这么多做一个全新的服务可以吗??我是新人……我只想知道
  • 我认为是的,这是一个好主意,因为如果您想在这之后不仅在这两个组件中使用这些常量,而且在更多其他组件中使用这些常量,这将不会花费您将来的任何更改
  • True .. 我只是创建一个类,将常量保留在那里并在任何需要的地方导入类而不是提供服务...我并不否认您的解决方案。只是想深入了解..我对角度几乎一无所知
  • 这也是一个很好的解决方案,如果你只是为了声明一些常量并且它比我的解决方案更好
  • 我从您的回复中得到了一些信心。谢谢哈立德.. 欣赏它
【解决方案2】:

textngOnInit方法的局部变量。它只存在于该方法中,并在该方法存在时消失。您需要将其设为 ChildComponent 类的实例字段:

export class ChildComponent implements OnInit {
   text: string;

   ngOnInit() {
       this.text = 'TEXT HERE';
   }
}

【讨论】:

  • 是的,我试过了,但无法从父组件访问。它说孩子在尝试打印时未定义
  • 那么说明父模板不包含任何子组件。
  • 确实如此。当我运行应用程序时,它会显示子组件。但是当我尝试从父级访问其常量之一时..使用@ViewChild,它不起作用
  • 如果您不发布重现问题的完整最小示例,我们将无能为力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
相关资源
最近更新 更多