【问题标题】:@Optional() @Host() throws "Cannot instantiate cyclic dependency!" Error@Optional() @Host() 抛出“无法实例化循环依赖!”错误
【发布时间】:2018-05-15 16:58:32
【问题描述】:

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

当我使用 @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;
    }

  }

}

【问题讨论】:

  • 如果你想在 dom 树中注入除自身以外的相同组件,请尝试使用 @SkipSelf
  • 这似乎解决了问题。非常感谢

标签: angular angular5 angular6


【解决方案1】:

如果您需要在服务器上生成 HTML,请将其全部生成在服务器上并将其放入 [innerHTML] 或将其托管在不同的服务器上并嵌入 iframe。你所做的不是 Angular 的用途。

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

constructor(private host: ElementRef) {}

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

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 2017-05-05
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多