首页 > 解决方案 > 使用 AOT 时出现 Angular 6 编译错误

问题描述

我最近被迫使用 AOT 并且在生产中没有正确编译模板。当我尝试一个空白项目时,它运行良好,但在我的巨型应用程序中存在问题。

像这样的东西:

@Component({
  selector: 'app-c3',
  template: '<ng-template #container></ng-template>',
  styleUrls: [],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class App3Component {
  _container: ViewContainerRef = null;

  @ViewChild('container', { read: ViewContainerRef })
  set container(value: ViewContainerRef) {
    console.log('set');
    this._container = value;
  }

  get container(): ViewContainerRef {
    return this._container;
  }
}

编译为

function View_App3Component_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵvid"](2, [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵqud"](402653184, 1, { container: 0 }), (_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵand"](16777216, [[1, 3], ["container", 2]], null, 0, null, View_App3Component_1))], null, null); }

但是,在我的巨型应用程序中,它是这样编译的:

function View_DynamicComponent_0(_l) { return _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵvid"](2, [(_l()(), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵand"](0, [["container", 2]], null, 0, null, View_DynamicComponent_1))], null, null); }

通过再分析一点,我发现这container被视为 anchorDef( ɵand) 而不是queryDef( ɵqud)。什么可能导致此错误?我如何进一步研究以找出anchorDef在这种情况下输出 an 的原因。

标签: angular6angular-compiler

解决方案


找了半天,才发现问题出在一个层次类中缺少一个导出。比如这样:

/*export*/ class DynamicComponentBase {
  @ViewChild('container', { read: ViewContainerRef })
  container: ViewContainerRef;
}

@Component({
  selector: 'tn-dynamic',
  template: `<ng-template #container></ng-template>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DynamicComponent extends DynamicComponentBase {
}

通过添加导出,编译器创建了正确的东西。

我在 Angular 团队中打开了一个错误。

https://github.com/angular/angular/issues/24543


推荐阅读