【问题标题】:Get ContentChildren of downgraded ng2 component获取降级 ng2 组件的 ContentChildren
【发布时间】:2019-01-22 22:03:57
【问题描述】:

我有一个使用 upgradeAdapter 引导并使用降级的 ng2 组件的 ng1 应用程序。

但是我遇到了@ContentChildren 装饰器的问题。 @ContentChildren 似乎没有看到已降级为 ng1 指令的 ng2 组件。

Plunker:http://plnkr.co/edit/aAoTsTtsJgZXjX3mswcN

父组件

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1><ng-content></ng-content>',
    directives: [ChildCmp]
})
export class AppComponent {
  @ContentChildren(ChildCmp) members = new QueryList();

  ngAfterContentInit() {
    console.log(this.members); //always with length 0
  }

}

子组件

@Component({
    selector: 'child-cmp',
    template: '<h2>Child</h2>'
})
export class ChildCmp { }

引导

var upgradeAdapter = new UpgradeAdapter();
angular.module('ng1App').directive('myApp', upgradeAdapter.downgradeNg2Component(AppComponent));
angular.module('ng1App').directive('childCmp', upgradeAdapter.downgradeNg2Component(ChildCmp));
upgradeAdapter.bootstrap(document, ['ng1App']);

【问题讨论】:

    标签: angular


    【解决方案1】:

    我遇到了同样的问题。但是有一个解决方法:

    创建一个 Angular 2 包装器组件,该组件在其模板中使用父组件和子组件。在此组件中,您导入父组件和子组件并将它们定义为 @Component 配置中的指令。然后你只需降级你的包装器组件并在你的 html 中使用这个。

    【讨论】:

    【解决方案2】:

    我创建了一个包装模块来解决这个问题。

    @NgModule({
        imports: [],
        declarations: [
            WrapComponent,
            ParentComponent,
            ChildComponent
        ],
        exports: [
            WrapComponent,
            ParentComponent,
            ChildComponent,
        ],
        entryComponents:[WrapComponent],
    })
    export class WrapModule {
        constructor(){
            console.log('WrapModule');
        }
    }
    

    例如:Plunker

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2019-09-05
      • 2023-02-03
      相关资源
      最近更新 更多