如果ViewChild没有在模板中被引用,是否可以将其标记为私有?
我已经能够做到这一点,然后使用'--prod‘标志构建和服务,并且没有遇到错误。我目前使用的是Angular 7。
@ViewChild(HelloComponent) private helloComponent;
下面是我所讨论的内容的堆栈闪电战:
https://stackblitz.com/edit/angular-vxbpuk?file=src%2Fapp%2Fapp.component.ts
我想我有使用aot的stackblitz,但你可以在本地验证同样的事情。
编辑:我很抱歉之前没有提出这个问题,但是angular文档中的这段回复让我犹豫了一下:
https://angular.io/guide/aot-compiler#phase-2-code-generation
修饰的组件类成员必须是公共的。不能将@Input()属性设置为私有或内部。
但正如@GCSDC已经在下面指出的那样,Angular团队似乎在他们的示例中使用了私有成员:
https://angular.io/guide/component-interaction#parent-calls-an-viewchild
发布于 2018-12-05 04:03:35
看起来是的,这是可以的,因为你可能会发现它也在官方的角度基础指南上做了,位于:
组件&模板>组件交互> Parent calls an @ViewChild()
@ViewChild(CountdownTimerComponent)私有timerComponent: CountdownTimerComponent;
发布于 2018-12-05 04:04:57
是的,这样做是可以的。由于此变量的作用域仅限于component
类,因此我们可以将其声明为private
并使用。
@ViewChild
是为了在component
内部与子component
交互而使用的,所以我们可以让它保持private
。
发布于 2018-12-05 04:43:32
private
和public
语法是对javascript语言的增强,用于typescript transpiler中的“静态分析”,我建议您尝试playground如何将typescript转换为JS。所以基本上,这是一种让任何阅读代码的人都能了解变量/函数的作用域的方法。类内的简单变量的示例是它们都转换为相同的JS private var1: number = 0
和public var1: number = 0
转换为this.var1 = 0
然而!在某些情况下,你可能真的想从父组件访问@ViewChild,但在这种情况下,你必须将其设置为@ViewChild(HelloComponent) public helloComponent;
,否则将会出现“编译/转译”错误。如果您想更清楚地了解作用域在哪里,请将其保留为private
,而不是像这样使用getter/setter:
export class MyComponent {
@ViewChild(HelloComponent) private _helloComponent;
get helloComponent(): any {
return _helloComponent;
}
set helloComponent(set: any) {
this._helloComponent = set;
}
}
https://stackoverflow.com/questions/53620472
复制相似问题