【发布时间】:2020-01-03 00:38:53
【问题描述】:
我的导师告诉我,“在 Angular 中,我们可以通过导入该服务来使用任何服务中定义的函数,但我们不能在任何其他组件中导入组件。要使用在任何其他组件中定义的函数,我们需要使用@ViewChild(组件名称)。”
但是当我尝试在不使用@viewChild的情况下调用其他组件中的某个组件的函数时,我成功了,并且没有发生任何错误。
请参考下面的例子来理解场景:
CASE1:在不使用@ViewChild的情况下调用其他组件中的组件函数
假设我们有一个组件“testcomponent”,并且在该组件中我们有一个“hello”函数,如下所示:
testcomponent.component.ts
import { Component, OnInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-testcomponent',
templateUrl: './testcomponent.component.html',
styleUrls: ['./testcomponent.component.css']
})
export class TestcomponentComponent implements {
constructor(){}
hello(){
console.log("Hello ABC");
}
}
为了在“app”组件中使用“testcomponent”组件的“hello”功能,我尝试了以下方法:
app.component.ts
import { Component} from '@angular/core';
import { TestcomponentComponent } from './testcomponent/testcomponent.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
constructor(private testcomponent : TestcomponentComponent ){};
ngAfterViewInit(){
this.testComponent.hello();
}
}
这里“Hello ABC”在控制台中打印出来,没有发生任何错误。
CASE2:使用@ViewChild调用其他组件中的组件函数
现在考虑我在“app.component.ts”文件中使用@ViewChild 调用“testcomponent”组件的“hello()”函数的情况:
import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
@ViewChild(TestcomponentComponent,{static:false}) viewChildOnComponentSelector : TestcomponentComponent;
ngAfterViewInit(){
this.viewChildOnComponentSelector.hello();
}
}
既然在 CASE1 中我能够在“app”组件中调用“testcomponent”的“hello()”方法,那么为什么我们需要像在 CASE2 中那样需要@ViewChild?
另外请解释一下,如果我们可以通过导入任何其他组件中的任何组件的功能(如在CASE1中),那么调用组件或服务的功能有什么区别?
【问题讨论】:
标签: javascript angular angular-services angular-components viewchild