Angular 从父组件访问子组件中的常量
我有两个组件,我想在单击时从父组件打印子组件中的文本 父组件:Angular 从父组件访问子组件中的常量,angular,typescript,Angular,Typescript,我有两个组件,我想在单击时从父组件打印子组件中的文本 父组件: import {Component, OnInit, ViewChild} from '@angular/core'; @Component({ selector: 'parent', templateUrl: 'parent.html' }) export class ParentComponent implements OnInit { @ViewChild(ChildComponent) child; cons
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...
}
我是个新手。我只是想知道如何使它工作,我想让一些常数在一个点上,并由其他人共享。不必,常数必须仅在子组件中。只是需要一个好的建议,如何使它与一个好的编码策略工作
这对我不起作用
谢谢我的解决方案是在这两个组件之间创建共享服务
/// 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){}
}
text
是ngOnInit
方法的局部变量。它只存在于该方法中,并且在该方法存在时消失。您需要使其成为ChildComponent类的实例字段:
export class ChildComponent implements OnInit {
text: string;
ngOnInit() {
this.text = 'TEXT HERE';
}
}
发布您的父组件模板,您需要使用@input您应该使用
@Output
参考此链接这是一个很好的解决方案,但只想知道在我的情况下这是否是一个好主意。在我的大型应用程序中,我只有3个常量字符串,我只想与两个组件共享。仅仅为了这么多就可以做一个全新的服务吗??我是新来的。。。我只是想知道,我想是的,这是个好主意,因为如果你想在这之后,不仅在这两个分量中,而且在更多的其他分量中,使用这些常数,这不会让你在未来发生任何变化。。我只是创建一个类,将常量保留在那里,然后在任何需要的地方导入该类,而不是创建一个服务,怎么样。。。我不是否认你的解决办法。只是想深入了解。。我几乎不知道angularit也是一个很好的解决方案,如果你只声明一些常数,它比我的解决方案好,我从你的回答中得到了一些信心。谢谢你,哈立德。。感谢您是的,我尝试过,但无法从父组件访问。当它试图打印时,表示子模板未定义,然后表示父模板不包含任何子组件。确实如此。当我运行应用程序时,它会显示子组件。但是当我试图从父级访问它的一个常量时。。使用@ViewChild,它不起作用。如果您不发布一个完整的最小示例来重现问题,我们将无能为力。