@Optional() @Host() 抛出"Cannot instantiate cyclic dependency!"错误



我的问题是,我有一个服务器生成在运行时编译的代码。代码应主要管理表单数据。因为数据结构未知
,所以我需要一个能够与其主机(同一组件(通信的组件。

当我使用 @Optional(( @Host(( 装饰器时,我仍然得到"无法实例化循环依赖!错误。

有没有办法解决这个问题或其他解决方案建议。

编辑:https://stackblitz.com/edit/angular-3zjnog?file=src%2Fapp%2Fapp.module.ts

这就是我的镇定的样子。

import { Component, OnInit, Input, AfterViewInit, Optional, Host } from '@angular/core';
@Component({
selector: 'app-mycomponent',
templateUrl: './data.component.html',
styleUrls: ['./data.component.css']
})
export class DataComponent implements AfterViewInit {
host: any;
@Input() data: any = null;
constructor(
@Optional() @Host() host: DataComponent
) {
this.host = host;
}
ngAfterViewInit() {
if (!this.data) {
this.data = this.host.data;
}
}
}

如果需要在服务器上生成 HTML,请在服务器上生成所有 HTML 并将其放入 [innerHTML] 中,或者将其托管在不同的服务器上并嵌入 iframe。你正在做的事情不是Angular的目的。

至于这个问题,你不需要@Host((。只需使用:

constructor(private host: ElementRef) {}
ngAfterViewInit() { this.host.nativeElement.focus(); } //with focus-trigger as example

最新更新