Directive differences in Angular

Asked

Viewed 1,536 times

6

I would like to know the difference between the statements of directives.

For example:

ng-for=""
*ngFor="" (o que é esse asterisco?)
ngFor=""
[ngStyle]

I’ve seen and used them, but I haven’t found the differences.

1 answer

9


ng-for was used in Angularjs or 1.X versions

ngFor without the asterisk is wrong and generates an error.

The correct way to do it in versions from angle 2.x is with *ngFor, this why the *ngFor as well as the *ngIf and others are called structural directives. These directives manipulate the gift directly so the asterisk is a message for the angular to evaluate them first. Remember that you cannot use two in the same element.

According to the tag documentation:

<div *ngIf="hero" class="name">{{hero.name}}</div>

flipped

<ng-template [ngIf]="hero">
  <div class="name">{{hero.name}}</div>
</ng-template>

i.e., Angular creates this tag ng-template around your div in that case and evaluate if before deciding whether to add div to the gift or not. The ng-template is a ghost tag that does not exist in the gift(does not disturb the css) really and makes some logic.

And [ngStyle] and another topic, basically you can link a property of an html tag to a variable in your Typescript. For example: in your html

<a [href]="minhaUrl">link</a>

in your Component

export class AppComponent {
  minhaUrl='https://google.com'
}

and equivalent to

 <a href="https://google.com">link</a>

With the advantage that you can change the value in this case of myUrl and the property would change accordingly.

Note that in one case you pass the name of a variable that contains the value and in the other you pass the value directly.

  • 1

    Excellent Eduardo! That’s what I was looking for. A question: is there ngStyle, without the clasps? Or even *ngStyle?

  • @Not marcogarcia, what you can do is [ngStyle]="'value'" notice the single quotes between the double quotes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.