【问题标题】:Call Web Component Function from Angular从 Angular 调用 Web 组件函数
【发布时间】:2021-07-13 06:52:55
【问题描述】:

我想调用我在 Angular 10 项目中使用的 Web 组件的函数。

假设我有一个名为 Foo 的 Angular 组件:

foo.component.ts:

export class FooComponent implements OnInit, OnDestroy {
   @ViewChild('bar') bar: any;
   
   constructor() {  }

   ngOnInit(): void {
    //  this.bar.hello('world')
   }
}

foo.component.html:

<h1>FOO</h1>
<wc-bar></wc-bar>

webComponent bar 是用 VueJS 构建的,并且有一个名为 hello 的函数,我该如何调用该函数?

【问题讨论】:

  • Web 组件是否作为 NPM 模块依赖项包含在内?如果是这样,您可以尝试导入元素并在 Angular 控制器中调用该函数。

标签: angular web-component


【解决方案1】:

我相信它应该这样工作:

foo.component.ts:

export class FooComponent implements OnInit, OnDestroy {
   @ViewChild('bar') bar: ElementRef<Bar>; // if you have `Bar` typings

   ngAfterViewInit(): void { // According to https://angular.io/api/core/ViewChild view queries are set before the ngAfterViewInit
      this.bar.nativeElement.hello('world')
   }
}

foo.component.html:

<h1>FOO</h1>
<wc-bar #bar></wc-bar>

【讨论】:

    猜你喜欢
    • 2018-01-22
    • 2020-12-22
    • 2018-11-18
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2019-11-20
    • 2017-12-18
    • 2021-04-07
    相关资源
    最近更新 更多