Angular ViewChild组件间通信demo

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Angular ViewChild组件间通信demo

Jovie   2022-12-13 我要评论

- ViewChild

这篇文章是Angular中组件间通信系列的一部分。虽然你可以从任何地方开始,但最好还是从头开始,对吗?

我们现在进入了Angular中组件间交流的最后一个方法。这是一个我不确定是否真的应该写出来的方法。你看,在我看来,使用ViewChild来让组件之间相互交流,是最后的手段。它不是那种反应式的,而且经常遇到各种竞赛条件,因为你没有使用像EventEmitters和数据绑定这样的东西,而是直接调用方法。

由于上述原因,我打算把这段话说得简短一些,因为在大多数情况下,你不会使用ViewChild在组件之间进行通信,但知道它是一种选择还是很好的。

通过ViewChild调用一个方法

想象一下,我有一个像这样的AppComponent:

import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild(ChildComponent, {static : false}) childComponent : ChildComponent;
  runChild() {
    this.childComponent.run();
  }
}

它也有像这样的HTML:

<button (click)="runChild()">Click Me</button>
<app-child></app-child>

我们现在有一个AppComponent,有一个按钮,当点击时,将 "运行 "我们的子组件。

还注意到我们使用了@ViewChild()指令来寻找HTML中的ChildComponent。有几种不同的方法可以做到这一点,例如,你可以在你的HTML中使用#name格式,然后用这个名字来寻找孩子,但重要的是,我们可以使用@ViewChild()来寻找html中的孩子元素,并获得它们的引用。

我们的ChildComponent看起来像这样:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  run() {
    //Maybe a bunch of logic here. And then we set a message. 
    console.log("Run Successfully!" );
  }
}

没有太多花哨的东西。在运行这个解决方案时,当我们点击AppComponent中的按钮时,它就会调用ChildComponent的运行方法,一切都很好!这就是我们的解决方案。所以,首先要进入的是。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们