繁体   English   中英

从组件 Angular 调用一个组件的函数

[英]Call function from one component from a component Angular

我是 Angular 的初学者。 我一直面临着从组件调用组件中的方法的问题,它们与它们无关。 我在互联网上关注了很多教程,但没有找到解决方案。

所以细节是:有2个不相关的组件。 第一个组件有一个按钮,如果我单击该按钮,来自第一个组件的字符串应该被发送到第二个组件中的一个函数,并且在该函数中它应该将字符串显示到控制台中。 但我在这里面临的问题是该函数在我单击之前只调用一次,它只显示值“111”,这是默认值。 请帮我

第一个组件:

 export class FirstComponent implements OnInit{ constructor(location:Location, private renderer : Renderer2, private element : ElementRef, private router: Router, private httpClient: HttpClient, private servic: MainService) { } clickMe() { this.servic.sendMessage("001"); } }

第二部分:

 export class SecondComponent implements OnInit { clickEventSubs:Subscription; constructor(public servic: MainService, private spinner: NgxSpinnerService, private router: Router){} this.clickEventSubs = this.servic.receiveMessage().subscribe(message => { this.toggle(message); }) public toggle(state: string){ console.log(state); } }

共享服务:

 @Injectable({ providedIn: 'root' }) export class MainService { private message = new BehaviorSubject<string>("111"); sendMessage(mess:string) { this.message.next(mess); } receiveMessage(): Observable<any> { return this.message.asObservable(); } }

当组件之间的关系是Child > Parent -通过 @viewChild() 共享日期

在第一个组件中,使用 @ViewChild() 并将第二个组件名称作为参数传递 -

@ViewChild(SecondComponent) secondChildView!: SecondComponent;

然后在第一个组件的函数中调用第二个组件的函数——

 import {ViewChild} from '@angular/core';

 export class FirstComponent implements OnInit{
 @ViewChild(SecondComponent) secondChildView!: SecondComponent;

 constructor() {}
 
   clickMe() {
     this.secondChildView.toggle('001'); 
  }
}

每当您调用 clickMe 函数时,它都会调用第二个组件的切换函数,您将从第一个组件获取切换函数中的值。

export class SecondComponent implements OnInit {

 constructor(){} 

 public toggle(state: string){
  console.log(state);
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM