Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a "template reference variable" with Angular 4?

Tags:

angular

pug

I am trying to figure how to use a template reference variable in a .pug template.

For example: div(#var) will throw an error:

compiler.es5.js:1694 Uncaught Error: Template parse errors: There is no directive with "exportAs" set to "#var" (" ... 

The cause is that pug will render as :

<div #var="#var"> ...

Angular will then fail.

like image 546
Jesus Segnini Avatar asked Jan 30 '23 11:01

Jesus Segnini


1 Answers

From the doc:

Template reference variables ( #var )

A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.

So, you just need <div #var > ,The #var declares a var variable on this <div> element.

In most cases, Angular sets the reference variable's value to the element on which it was declared.... But a directive can change that behavior and set the value to something else, such as itself. The NgForm directive does that

If you assign something in the template ref variable, it should be a directive or a component, for example: #var="ngForm" which ngForm is a built-in directive.

So that's why you get an error: There is no directive with "exportAs" set to "#var"

Because #var (you assigned with: <div #var="#var">) is not a component nor a directive,

Now for jade (pug), if you want a null attribute,you should set the compiler to compile to HTML doctype because the default behaviour of pug is to set an attribute value which is the same name on the attribute:

default behaviour:

div(#var) compiled to: <div #var="#var"></div>

div(hidden) compiled to <div hidden="hidden"></div>

with doctype html:

div(#var) compiled to: <div #var></div>

div(hidden) compiled to <div hidden></div>

Or you can just put in beginning of the file:doctype html for each file you want this.

like image 180
Fetrarij Avatar answered Feb 01 '23 00:02

Fetrarij