微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用选择器作为当前组件的子组件树中定义的任何提供者的 ViewChild 装饰器的用例

如何解决使用选择器作为当前组件的子组件树中定义的任何提供者的 ViewChild 装饰器的用例

Angular ViewChild Documentation 中,提到:

支持以下选择器:

在当前组件的子组件树中定义的任何提供者(例如@ViewChild(SomeService) someService: SomeService)

在哪个用例中,子组件提供者需要是父组件中 ViewChild 中的选择器?我无法想到所提供的此功能的用例。我也无法通过互联网搜索它。

Angular University Blog about ViewChild Decorator 也没有提及这一点。

解决方法

ViewChild 使访问子组件和调用方法或访问子组件可用的实例变量成为可能。

假设我们有一个 ChildComponent。理想情况下,您将使用@angular/cli 来生成您的组件:

ng generate component child --flat

否则,您可能需要创建 child.component.css 和 child.component.html 文件并手动将其添加到 app.module.ts:

app.module.ts
import { ChildComponent } from './child.component';
...
@NgModule({
  declarations: [
    AppComponent,ChildComponent
  ],...
})

我们将向 ChildComponent 添加一个 whoAmI 方法,它会返回一条消息:

child.component.ts

whoAmI() {
  return 'I am a child component!';
}

接下来,我们将在我们的应用模板中引用该组件:

app.component.html <app-child>child works!</app-child>

现在,我们可以像这样从父组件类中使用 ViewChild 调用 whoAmI 方法:

app.component.ts
import {
  Component,ViewChild,AfterViewInit
} from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'],})
export class AppComponent implements AfterViewInit {
  @ViewChild(ChildComponent) child: ChildComponent;
  ngAfterViewInit() {
    console.log(this.child.whoAmI()); // I am a child component!
  }
}

在浏览器中查看应用程序时,控制台日志将显示:

输出

I am a child component!

父组件能够调用子组件的 whoAmI 方法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。