dzenesiz
dzenesiz

Reputation: 1552

Angular - template reference on ng-content

I need to render dynamic content around an input in Angular app.

My idea was to create a custom component, and then use ng-content to bind the behavior to that input. Like so:

<my-wrapper>
    <input type="text" otherAttributes...>
</my-wrapper>

And my wrapper would be something like below.

HTML:

<span>
    <ng-content #myRef></ng-content>
    <button (click)="perform(myRef)">Click me!</button>
</span>

And .ts function:

perform(myRef: HTMLIntpuElement) {
    myRef.value = 'something else';
}

Now, I know that ng-content doesn't actually exist, and that I can't really place reference on it since that content can be more than one element, but is there a way to get to it the "Angular way", instead of using brute force i.e. native element?

Upvotes: 0

Views: 1703

Answers (1)

P&#233;ter
P&#233;ter

Reputation: 322

I think your problem is solvable with @ContentChildren/@ContentChild. They are similar with @ViewChildren/@ViewChild but @ContentChild looks into ng-content while @ViewChild not.

 <input type="text" #myRef>

and in typescript file:

 @ContentChildren('myRef') items: QueryList<ElementRef>;

Upvotes: 3

Related Questions