- 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的运行方法,一切都很好!这就是我们的解决方案。所以,首先要进入的是。
以上就是angular viewchild组件间通信demo的详细内容,更多关于angular viewchild组件通信的资料请关注代码网其它相关文章!
发表评论