gpt4 book ai didi

angular - 如何使用 new 关键字实例化 Angular 组件?

转载 作者:行者123 更新时间:2023-12-03 23:40:11 25 4
gpt4 key购买 nike

如何使用 new 关键字实例化 Angular 组件?
想象一下以下作为无模板组件:

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

@Component({
selector: 'my-component',
})
export class MyComponent {
constructor(private myService: MyService)
}

我知道只有在模板中找到选择器标签时才会实例化 Angular 组件。
但...
如何使用 new 关键字实例化上述内容?
因为我的组件不需要模板。
但它应该是 @component 的 Angular 分量装饰师。 (因为我需要依赖注入(inject)的特性)
但问题是,当我创建一个新组件时,如下所示:
const comp = new MyComponent()
它还要求在实例化时也将服务实例传递给它的构造函数。像这样”
const comp = new MyComponent(new MyService())
当我们再次传入的服务依赖于其他服务时,这变得更加困难。
像这样...
const comp = new MyComponent(new MyService(new AnotherService(new YetAnotherService(... so on))))
那么有没有解决方法呢?
Angular 的 DI 很好。因为我们没有任何类似上述的问题。它会自动创建所有注入(inject)的服务。 new 也有可能吗?关键词。
注意 我尝试使用普通的 typescript 类。但我还是不喜欢。我想使用 Angular 组件本身。
那可能吗?

最佳答案

我强烈建议不要这样做。 Angular 不是为此而生的,变更检测可能无法正常工作,您必须自己管理组件。
但是无论如何,如果你想动态创建一个组件,你可以使用ComponentFactoryResolver :

import { Component, ComponentFactoryResolver, Injector, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'hello'
})
export class HelloComponent {
@Input() get name(): string { return this._name; }
set name(value: string) {
this._name = value;
this.nameChange.emit(value);
}
private _name: string;

@Output() nameChange = new EventEmitter<string>();
}

@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector
) { }

ngOnInit() {
const factory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
const helloRef = factory.create(this.injector);

const hello = helloRef.instance;

// Subscribe to output
const subscription = hello.nameChange.subscribe(name => console.log('name changed', name));

// Set name input
hello.name = 'Hello!';

// When you are done with the component, it must be destroyed
subscription.unsubscribe();
helloRef.destroy();
}
}

由于您没有模板,因此在您的情况下无关紧要,但是如果您需要在动态创建的组件中进行更改检测,则需要将它们附加到应用程序:
export class AppComponent  {
constructor(
// ...
private applicationRef: ApplicationRef
) { }

ngOnInit() {
// create helloRef ...
this.applicationRef.attachView(helloRef.hostView);

// ...

// Destroy the component
this.applicationRef.detachView(helloRef.hostView);
helloRef.destroy();
}
}

关于angular - 如何使用 new 关键字实例化 Angular 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66181944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com