美文网首页
angular 模板语法

angular 模板语法

作者: 不染事非 | 来源:发表于2019-08-05 16:05 被阅读0次
1.插值表达式 (Interpolation) {{...}}
<p>The sum of 1 + 1 is {{1 + 1}}</p>
2.表达式上下文 (Expression context)
{{title}}
<span [hidden]="isUnchanged">changed</span>

二.绑定语法

绑定的类型可以根据数据流的方向分成三类:

  • 从数据源到视图(source-to-view)
  • 从视图到数据源(view-to-source)
  • 双向的从视图到数据源再到视图(view-to-source-to-view)。
单向 source-to-view

语法 绑定类型
{{expression}} 插值表达式
[target]="expression" / bind-target="expression" Property, Attribute 类样式

单向 view-to-source

语法 绑定类型
(target)="statement" / on-target="statement" 事件

双向

语法 绑定类型
[(target)]="expression" / bindon-target="expression" 双向

绑定类型(插值表达式除外)有一个目标名,它位于等号左边,它是 Property 的名字(注意它不是 Attribute 的名字)。

绑定目标 (Binding targets)

Property 绑定类型
目标 范例
Element property <img [src]="heroImageUrl">
Component property <hero-detail [hero]="currentHero"></hero-detail>
Directive property <div [ngClass]="{special: isSpecial}"></div>
事件绑定类型
目标 范例
Element event <button (click)="onSave()">Save</button>
Component event <hero-detail (deleteRequest)="deleteHero()"></hero-detail>
Directive event <div (myClick)="clicked=$event" clickable>click me</div>
双向绑定类型
目标 范例
Event and property <input [(ngModel)]="name">
Attribute 绑定类型
目标 范例
Attribute(例外情况) <button [attr.aria-label]="help">help</button>
CSS 类绑定类型
目标 范例
class property <div [class.special]="isSpecial">Special</div>
样式绑定类型
目标 范例
style property <button [style.color]="isSpecial ? 'red' : 'green'">
属性绑定 (Property binding) [property]
<img [src]="heroImageUrl">

上例说明:image 元素的 src 属性会被绑定到组件的 heroImageUrl 属性上。

绑定目标

两种写法:

<img [src]="heroImageUrl">

![](heroImageUrl)

三.内置指令

常见的内置属性型指令:

  • NgClass 添加或移除一组CSS类
  • NgStyle 添加或移除一组CSS样式
  • NgModel 双向绑定到 HTML 表单元素
NgClass

示例:组件方法 setCurrentClasses 可以把组件的属性 currentClasses 设置为一个对象,它将会根据三个其它组件的状态为 true 或 false 而添加或移除三个类

currentClasses: {};
setCurrentClasses() {
  this.currentClasses =  {
    saveable: this.canSave,
    modified: !this.isUnchanged,
    special:  this.isSpecial
  };
}

把 ngClass 属性绑定到 currentClasses,根据它来设置此元素的 CSS 类:

<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>
NgStyle

ngStyle 需要绑定到一个 key:value 控制对象。 对象的每个 key 是样式名,它的 value 是能用于这个样式的任何值。

currentStyles: {};
setCurrentStyles() {
  // CSS styles: set per current state of component properties
  this.currentStyles = {
    'font-style':  this.canSave      ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold'   : 'normal',
    'font-size':   this.isSpecial    ? '24px'   : '12px'
  };
}

<div [ngStyle]="currentStyles">
  This div is initially italic, normal weight, and extra large (24px).
</div>
NgModel

要使用 ngModel 需要导入 FormsModule 模块。

import { NgModule } from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular

/* Other imports */
@NgModule({
  imports: [
    BrowserModule,
    FormsModule  // <--- import into the NgModule
  ],
  /* Other module metadata */
})
export class AppModule { }

使用 ngModel 实现双向数据绑定。

<input [(ngModel)]="currentHero.name">

该语句实际上隐藏了其实现细节:

<input [ngModel]="currentHero.name"
       (ngModelChange)="currentHero.name=$event">

如果需要做一些不同的处理,就不能使用 [(ngModel)] 语法,而应写成扩展的方式:

<input [ngModel]="currentHero.name"
       (ngModelChange)="setUppercaseName($event)">

ngModel 指令只能用在支持 ControlValueAccessor 的元素上。

四. 内置结构型指令

常见的内置结构型指令:

  • NgIf
  • NgFor
  • NgSwitch
NgIf
<hero-detail *ngIf="isActive"></hero-detail>

别忘了 ngIf 前面的星号( * )。

NgFor
<div *ngFor="let hero of heroes">{{hero.name}}</div>
NgSwitch

NgSwitch 由三个指令组成:

  • 属性型指令 NgSwitch
  • 结构型指令 NgSwitchCase
  • 结构型指令 NgSwitchDefault
<div [ngSwitch]="currentHero.emotion">
  <happy-hero    *ngSwitchCase="'happy'"    [hero]="currentHero"></happy-hero>
  <sad-hero      *ngSwitchCase="'sad'"      [hero]="currentHero"></sad-hero>
  <confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></confused-hero>
  <unknown-hero  *ngSwitchDefault           [hero]="currentHero"></unknown-hero>
</div>
模板引用变量

使用井号 # (或 ref-)来声明一个模板引用变量。The#phone declares a phone variable on an <input> element.

<input #phone placeholder="phone number">
或者写成
<input ref-phone placeholder="phone number">
输入输出属性 @Input 和 @Output
声明输入和输出属性(目标属性必须被显式的标记为输入或输出。)

HeroDetailComponent.hero 是属性绑定的目标。 HeroDetailComponent.deleteRequest 是事件绑定的目标。

<hero-detail [hero]="currentHero" (deleteRequest)="deleteHero($event)">
</hero-detail>

方法1:使用装饰器 @Input() 和 @Output()。

@Input()  hero: Hero;
@Output() deleteRequest = new EventEmitter<Hero>();

方法2:通过元数据数组。

@Component({
  inputs: ['hero'],
  outputs: ['deleteRequest'],
})

两种方法不可同时使用。

给输入输出属性起别名

方法1:把别名传进 @Input / @Output 装饰器,就可以为属性指定别名:

@Output('myClick') clicks = new EventEmitter<string>(); //  @Output(alias) propertyName = ...

方法2:在 inputs 和 outputs 数组中为属性指定别名。 语法(属性名:别名)

@Directive({
  outputs: ['clicks:myClick']  // propertyName:alias
})

模板表达式操作符

管道操作符 |

管道是一个简单的函数,它接受一个输入值,并返回转换结果。

<div>Title through uppercase pipe: {{title | uppercase}}</div>

还能对管道使用参数:

<div>Birthdate: {{currentHero?.birthdate | date:'longDate'}}</div>
安全导航操作符 ( ?. ) 和空属性路径

Angular 的安全导航操作符 (?.) 用来保护出现在属性路径中 null 和 undefined 值。示例:

The current hero's name is {{currentHero?.name}}

说明:当 currentHero 为空时,保护视图渲染器,让它免于失败。

相关文章

  • Angular4-学习笔记-4-模板语法

    学习资料来自 Angular.cn 与 Angular.io。 模板语法 在线例子 在 Angular 中,组件扮...

  • AngularJS 模板语法

    模板语法 模板是编写 Angular 组件最重要的一环,你至少需要深入理解以下知识点才能玩转 Angular 模板...

  • angular 模板语法

    1.插值表达式 (Interpolation) {{...}} 2.表达式上下文 (Expression cont...

  • angular-2

    angular基础模板语法 文本绑定 {{}} html绑定 [innerHTML]="xxx" 属性绑定 [属性...

  • vue 与react技术选形一些对比

    模板的区别 vue使用模板是初是由angular提出 react 使用jsx(jsx已经是标准) 模板语法上,我更...

  • Angular中的模板驱动表单和响应式表单

    1、模板驱动表单 根据angular模板语法,再结合专门的指令构建的表单。比如下面通过[(ngModal)],根据...

  • [Angular学习笔记]Angular模板语法

    模板语法 Angular 应用管理着用户之所见和所为,并通过 Component 类的实例(组件)和面向用户的模板...

  • Angular 语法大全

    今日上班的时候有看到一篇关于angular语法的总结,个人觉得不错,内容如下: 引导 NgModules 模板语法...

  • Vue 与 Angular

    无论在代码体积和性能上面,Vue都比Angular1、Angular2表现得优异许多。 1. 模板语法 Vue有许...

  • Angular 第二篇 | Angular 架构

    用angular扩展语法编写html模板,用组件类管理这些模板,用服务添加应用逻辑,用模块打包发布组件与服务。 以...

网友评论

      本文标题:angular 模板语法

      本文链接:https://www.haomeiwen.com/subject/tmjmdctx.html