<div>
@if (user.name as userName) {
{{ userName }}
}
</div>
<div>
@if (user.name) {
{{ user.name }}
}
</div>
I am wondering what is the difference between this two approaches? just a syntax? or something else? For example when using as
does it creates variable? What is happening under the hood?
2
Answers
The "as" keyword generates code that assigns the value to a temporary variable.
Use "as" for:
Cleaner template logic by introducing meaningful aliases.
Avoiding repetitive property access.
Avoid "as" when:
Not re-referencing the property within the block.
Unnecessary for clarity.
I don’t know how deep you want such an explaination to go.
if you really want to go down to each line of execution, I’m sorry.. I will not put hours into this question.
Basically this happens:
First of all, you have to keep in mind, what you are writing there, is a dialect that does resemble js, but isn’t.
So to not go into too much depth and keep this somewhat reasonable, let’s start at the point, where the parser will encounter a
@
symbol:https://github.com/angular/angular/blob/c213a4e15a594ff141cf312ad301128e7ed4127c/packages/compiler/src/ml_parser/lexer.ts#L206-L207
basically what you see there, is that when encountering an
@
, it will consume the continuing data as block.the consumption of that block will parse as follows:
https://github.com/angular/angular/blob/c213a4e15a594ff141cf312ad301128e7ed4127c/packages/compiler/src/ml_parser/lexer.ts#L245-L277
after all the blocks of your code are parsed, it will be thrown into angulars expression parser. (since
@
refers to an expression)this will also go through, and parse the
as
bindings.https://github.com/angular/angular/blob/c213a4e15a594ff141cf312ad301128e7ed4127c/packages/compiler/src/expression_parser/parser.ts#L1145-L1180
which will then go there:
https://github.com/angular/angular/blob/c213a4e15a594ff141cf312ad301128e7ed4127c/packages/compiler/src/expression_parser/parser.ts#L1202-L1223
and will then do a variable binding as seen here:
https://github.com/angular/angular/blob/c213a4e15a594ff141cf312ad301128e7ed4127c/packages/compiler/src/expression_parser/ast.ts#L343-L374
afterwards the bindings and other entities that drop out the AST compiler will be rendered here:
https://github.com/angular/angular/blob/c213a4e15a594ff141cf312ad301128e7ed4127c/packages/compiler/src/render3/view/template.ts#L2875-L2876
if you then go further into that function there, called
htmlAstToRender3Ast
, you will encounter a call toHtmlAstToIvyAst
which then goes further into roughly 600 more lines of code that do yet another AST to AST convertion..I could go further ofc, but as I said at the start, going deep will take a long time.
I hope you get a gist of how this somewhat works now.
essentially it parses this
as
expression as a variable expansion, likelet [foo, bar] = [1, 5]
in vanilla js. except in this case it’s more like[1, 5][0] as foo
also a small reminder: all this code is ran every time you compile a template.