如何使用contentChild获得组件中的ng-template和ngModel

问题描述 投票:0回答:1

我的要求是同时获得ngModelng-template

这是我访问ng-template的方式

@Component({
  selector: 'sample',
  template: `<ng-template [ngTemplateOutlet]="container"></ng-template>`
})
@ContentChild('container') container: TemplateRef<any>;

上面的代码可以访问ng-template,我可以在ngTemplateOutlet中显示它。

但是我无法访问ngModel

这是我尝试过的

@ContentChild(NgModel) model: NgModel; //undefined
this.container.elementRef.nativeElement // <!--container-->

Stackblitz

angular
1个回答
0
投票
我已经分叉了您的Stackblitz示例,并更改了几行:

Stackblitz

@ContentChild(NgModel) model: NgModel;

进入

@ContentChildren(NgModel) model: QueryList<NgModel>;

并订阅'model'变量的更改:

this.model.changes.pipe(first()).subscribe(res => { const ctrl = res.first as NgModel; console.log("ctrl", ctrl); });

© www.soinside.com 2019 - 2024. All rights reserved.