Sameer
Sameer

Reputation: 5188

How to get ng-template and ngModel in component using contentChild

My requirement is to get ngModel as well as ng-template

This is how I get access to ng-template

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

The above code gives access to ng-template I am able to display that in ngTemplateOutlet.

However I am not able to get access to ngModel

This is what I have tried

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

Stackblitz

Upvotes: 0

Views: 458

Answers (1)

Crazybutch
Crazybutch

Reputation: 835

I've forked your Stackblitz Example and changed few lines:

Stackblitz

@ContentChild(NgModel) model: NgModel;

into

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

And subscribe to changes of the 'model' Variable:

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

Upvotes: 1

Related Questions