这里的星号实际上是一个语法糖,后面的ngIf称之为microsyntax,即微语法。Angular会把进行解糖操作,替换成传统的实现。值得一提的是,后者也不会出现在最后生成的html代码里。
注意命名规范:NgIf是结构化指令的实现class,ngif是指令的属性名,应用在HTML代码里。
除了structural指令外,Angular常用的还有Component指令和属性指令两种。
A component manages a region of HTML in the manner of a native HTML element. Technically it’s a directive with a template.
An attribute directive changes the appearance or behavior of an element, component, or another directive. For example, the built-in NgStyle directive changes several element styles at the same time.
structural指令和host元素是1:1关系,attribute指令和host元素可以是N:1关系。
NgIf takes a boolean expression and makes an entire chunk of the DOM appear or disappear.
<p *ngIf="true"> Expression is true and ngIf is true. This paragraph is in the DOM. </p> <p *ngIf="false"> Expression is false and ngIf is false. This paragraph is not in the DOM. </p>
The *ngIf directive moved to the element where it became a property binding,[ngIf].
The rest of the
, including its class attribute, moved inside the element.
At minimum NgFor needs a looping variable (let hero) and a list (heroes).
NgFor至少需要一个列表(heroes)和展开这个列表的变量(let hero).使用微语法(一个字符串)配置结构性指令。微语法解析器把这个字符串里的内容解析成的属性:
The parser translates let hero, let i, and let odd into variables named let-hero, let-i, and let-odd.
As the NgFor directive loops through the list, it sets and resets properties of its own context object. These properties can include, but aren’t limited to, index, odd, and a special property named $implicit.
NgFor遍历list,在每次循环过程体内部设置它自己上下文对象的属性,比如index,odd和$implicit.
Template input variable
A template input variable is a variable whose value you can reference within a single instance of the template. 可以在模板的某一个具体实例内被使用。
还有一种情况,某些html元素要求其子元素必须是一种特殊的类型,比如的子元素必须是, 二者中间不能再引入或者等中间层级。像下图这种设计,最后是看不到下拉菜单的: