Currently am learning about Angular 4 introduced a new keyword : as
.
AS keyword – A new addition to the template syntax is the as keyword
is use to simplify to the let
syntax.
I have just implement this below code.
<div *ngIf="users | async as usersModel">
<h2>{{ usersModel.name }}</h2> <small>{{ usersModel.age }}</small>
</div>
I can't get much details from anywhere for this below questions.
users
object and userModel
object*. as
keyword?as
and let
in template?You have prepared the best example of using "as" keyword.
If you did not use it, your code would be less readable and it look like that:
<div *ngIf="users | async as usersModel">
<h2>{{ (users | async)?.name }}</h2> <small>{{ (users | async).age }}</small>
</div>
In this example users is Observable object. Thanks to as kayword, you can assign to userModel result of async pipe on Observable object. F.e.
if users is users: Observable<User>;
then usersModel is a result of async pipe on users variable, so it's like usersModel: User
object.
@EDIT for question about as and let
I can't tell you what is the difference between as and let, because these are two different things. let is a javascript variable type, that:
let allows you to declare variables that are limited in scope to the block
as is a Angular keyword, which can you assign result of method/pipe to other variable.
This is your first post so I remind: Angular is not programming language, but JavaScript framework. Most things in Angular is related with pure JS or TS.
Declaration of for loop in Angular is copy of declaration for loop by array from ECMAScript6, f.e.
for loop (ECMAScript6)
let iterable = [10, 20, 30];
for (let value of iterable) {
console.log(value);
}
for loop in component template
<div *ngFor="let user of users">
Keyword as is a shortcut of assigment to variable result of method, f.e for some pipe
some.pipe.ts
@Pipe({
name: 'somePipe'
})
export class SomePipe {
transform(value: number): number {
return number * 2;
}
}
using <div *ngIf="someValue | somePipe as otherValue">
is like:
let otherValue = SomePipe.transform(someValue);
You get it?
p.s: Last paragraph in my answer is only mental shortcut, of course. If you want know, how ngFor and ngIf directives works "inside", I recommend you to watch Nir Kaufman - Demystified Angular Directives lecture.