从一个组件到另一个组件的运行/发射器事件 [英] Run / emitter event from one component to another
问题描述
我创建了两个组件:( nav
和 app
).
在导航中,我具有函数 getnumber()
,该函数在执行时从总值中减去-1.
是否可以通过单击在应用程序组件中执行此功能?
我希望当单击应用程序组件的按钮时,该功能将在 nav
组件中执行并更新值.
当总值为5时,单击按钮将执行该功能,该值将变为4.
有人可以帮我申请吗?
谢谢
演示 >
导航
getnumber(){this.total = this.total-1;}
Nav.html
< p>导航</p>< p>总计:{{total}}</p>
您可以通过模板引用在另一个组件上调用公共方法.
app.component.html
< app-nav#nav></app-nav>< button(click)="nav.decrement()">执行decrement()导航组件</button>
nav.component.ts
total = 5;减量(){this.total = this.total-1;}
在HTML示例中, #nav
正在创建对 NavComponent
实例的称为 nav
的引用.现在,同一HTML文件中的任何其他元素都可以在该实例上调用公共函数.
演示: https://stackblitz.com/edit/angular-bw5jtp >
替代方法
您可以从component.ts中调用它,而不是直接在HTML中调用 #nav
.使用 @ViewChild
获取对该组件实例的引用.
app.component.ts
@ViewChild('nav',{static:true})nav:NavComponent;onClick():无效{this.nav.decrement();}
I created two components: (nav
and app
).
Within the nav I have the function getnumber()
which when executed subtracts -1 from the total value.
Is there a way to execute this function through a click but in the app component?
I intend that when clicking the button of the app component the function will be executed in the nav
component and the value updated.
As the total value is 5, when clicking the button the function is executed and the value becomes 4.
Can anyone help me apply this?
Thanks
nav.ts
getnumber(){
this.total = this.total - 1;
}
Nav.html
<p>
Nav
</p>
<p>
Total: {{total}}
</p>
You can call public methods on another component via a template reference.
app.component.html
<app-nav #nav></app-nav>
<button (click)="nav.decrement()">
Execute decrement() nav component
</button>
nav.component.ts
total = 5;
decrement() {
this.total = this.total - 1;
}
In the HTML example, #nav
is creating a reference called nav
to the NavComponent
instance. Any other elements in the same HTML file can now call public functions on that instance.
DEMO: https://stackblitz.com/edit/angular-bw5jtp
Alternative approach
Instead of calling #nav
directly in the HTML, you can call it from your component.ts. Use @ViewChild
to get a reference to the instance of the component.
app.component.ts
@ViewChild('nav', { static: true }) nav: NavComponent;
onClick(): void {
this.nav.decrement();
}
这篇关于从一个组件到另一个组件的运行/发射器事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!