簡體   English   中英

Angular 沒有噴油器的元件?

[英]Angular elements without injector?

我正在試驗 Angular 的自定義元素並試圖避免使用 Angular 的依賴注入

const MyElementElement = createCustomElement(MyElementComponent, { injector });
customElements.define('my-element', MyElementElement);

但是我無法在不傳遞注入器的情況下創建自定義元素

createCustomElement(MyElementComponent)

有沒有一種方法可以在不使用 Angular 的依賴注入的情況下使用自定義元素?

我不確定您的createCustomElement函數在做什么,但是如果您嘗試動態添加組件,這就是您想要遵循的模式。

import { Component, ComponentFactoryResolver, OnInit, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
    selector: 'app-something',
    templateUrl: './something.component.html',
    styleUrls: ['./something.component.scss']
})
export class SomethingComponent implements OnInit {
    @ViewChild('containerRef', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef;
    private readonly _cfResolver: ComponentFactoryResolver;
    constructor(_cfr: ComponentFactoryResolver) {
        this._cfResolver = _cfr;
    }

    ngOnInit() {
        const componentFactory = this._cfResolver.resolveComponentFactory(MyComponent);
        const componentRef = this.viewContainerRef.createComponent(componentFactory);
        // Component Ref then has access to all it's properties
        // So you can then do things like
        // componentRef.instance.myComponentProperty = 'something';
    }
}

在您的 HTML 中,放置以下標記的位置是您可以控制組件插入位置的方式:

<ng-template #containerRef></ng-template>

基本上,在您想要執行“動態操作”的ComponentFactoryResolver ,導入ComponentFactoryResolver以便您可以創建一個組件工廠。 一旦你有了那個工廠,你就可以將它插入到你的組件中。 如果您這樣做,動態組件中的注入器將被解析。 你不必傳入任何東西。

它不像做new MyComponent(...)那樣簡單

只需通過一個空的注射器

createCustomElement(MyElementComponent, Injector.create({ providers: [] }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM