这本书声明中的第二个指令在哪里
Where is the second directive in this book statement
嗨,我正在读一本关于 angular
的书
我得到下面的句子
对我来说,ngFor 是一个结构指令是很直观的。但是第二个在哪里?
谢谢
确实有两种类型的指令。
1) Structural Directives
2) Attribute Directives
但是在这个例子中只使用了一个指令,这就是 *ngFor
。这负责为 books
数组的每个对象创建一个 li
元素。
属性指令是一种可以应用于现有元素的指令。这允许您更改元素的属性。类似于您可以在每次迭代时获取索引,然后将其传递到属性指令中,并且一旦基于具有索引的条件,您可以通过更改 li
元素的属性来格式化 li
元素,例如 CSS通过属性指令设置样式。
我附上了属性指令的使用示例
指令Class
import { Directive, ElementRef, OnInit } from "@angular/core";
@Directive({
selector:'[appHighlight]'
})
export class HighlightText implements OnInit{
private theReference : ElementRef
constructor(theReference : ElementRef){
this.theReference = theReference;
}
ngOnInit(): void {
this.theReference.nativeElement.style.backgroundColor = "lightcoral";
}
}
模板中的用法
<p appHighlight>Directive Usage</p>
当使用选择器 [appHighlight]
将指令作为属性引用时,在元素 <p>
中 OnInit
挂钩中指令 backgroundColor
中定义的属性。您可以使用 Renderer2
或访问 nativeElement
属性 来更改您想要更改的属性,但建议使用 Renderer2
*ngFor
<-- 注意
*
。以 *
为前缀的指令通常是其他指令的缩写(通常是两个指令“合并”为一个指令)。
Angular 将 *ngFor 从星号 (*
) 语法转换为 <ng-template>
元素。
看看这段代码:
<div *ngFor="let hero of heroes">
{{hero.name}}
</div>
就像在做:
<ng-template ngFor let-hero [ngForOf]="heroes">
<div>{{hero.name}}</div>
</ng-template>
嗨,我正在读一本关于 angular
的书我得到下面的句子
对我来说,ngFor 是一个结构指令是很直观的。但是第二个在哪里?
谢谢
确实有两种类型的指令。
1) Structural Directives
2) Attribute Directives
但是在这个例子中只使用了一个指令,这就是 *ngFor
。这负责为 books
数组的每个对象创建一个 li
元素。
属性指令是一种可以应用于现有元素的指令。这允许您更改元素的属性。类似于您可以在每次迭代时获取索引,然后将其传递到属性指令中,并且一旦基于具有索引的条件,您可以通过更改 li
元素的属性来格式化 li
元素,例如 CSS通过属性指令设置样式。
我附上了属性指令的使用示例
指令Class
import { Directive, ElementRef, OnInit } from "@angular/core";
@Directive({ selector:'[appHighlight]' }) export class HighlightText implements OnInit{ private theReference : ElementRef constructor(theReference : ElementRef){ this.theReference = theReference; } ngOnInit(): void { this.theReference.nativeElement.style.backgroundColor = "lightcoral"; } }
模板中的用法
<p appHighlight>Directive Usage</p>
当使用选择器 [appHighlight]
将指令作为属性引用时,在元素 <p>
中 OnInit
挂钩中指令 backgroundColor
中定义的属性。您可以使用 Renderer2
或访问 nativeElement
属性 来更改您想要更改的属性,但建议使用 Renderer2
*ngFor
<-- 注意
*
。以 *
为前缀的指令通常是其他指令的缩写(通常是两个指令“合并”为一个指令)。
Angular 将 *ngFor 从星号 (*
) 语法转换为 <ng-template>
元素。
看看这段代码:
<div *ngFor="let hero of heroes">
{{hero.name}}
</div>
就像在做:
<ng-template ngFor let-hero [ngForOf]="heroes">
<div>{{hero.name}}</div>
</ng-template>