Angular支持 双向数据绑定

创建服务类:对于与特定视图无关并希望跨组件共享的数据或逻辑

模块变量:

1、 # 来声明一个模板变量,可在组件模板中的任何地方引用某个模板变量

<input #phone placeholder="phone number" />

<!-- lots of other elements -->

<!-- phone refers to the input element; pass its `value` to an event handler -->
<button (click)="callPhone(phone.value)">Call</button>

// phone 引用的是电话号码 <input> 。该按钮的 click 处理程序会把这个 <input> 的值传给该组件的 callPhone() 方法。

    如果在标准的 HTML 标记上声明变量,该变量就会引用该元素。

   如果该变量在右侧指定了一个名字,比如 #var="ngModel" ,那么该变量就会引用所在元素上具有这个 exportAs 名字的指令或组件

示例:

<form #itemForm="ngForm" (ngSubmit)="onSubmit(itemForm)">
  <label for="name">Name <input class="form-control" name="name" ngModel required />
  </label>
  <button type="submit">Submit</button>
</form>

<div [hidden]="!itemForm.form.valid">
  <p>{{ submitMessage }}</p>
</div>

<!---与原生的 <form> 元素不同, NgForm 指令有一个 form 属性。如果 itemForm.form.valid 无效,那么 NgForm 的 form 属性就会让你禁用提交按钮--->

2、模块变量作用域:

1)可以在包含此模板变量的模板中的任何地方引用它

2)不能在 结构型指令(如 *ngIf 和 *ngFor 或 <ng-template>这些边界之外访问其中的模板变量

3)同名变量在模板中只能定义一次,这样运行时它的值就是可预测的。

4)内部模板可以访问外模板定义的模板变量。

<input #ref1 type="text" [(ngModel)]="firstExample" />

<!-- New template -->
<ng-template [ngIf]="true">
  <!-- Since the context is inherited, the value is available to the new template -->
  <span>Value: {{ ref1.value }}</span>
</ng-template>

访问父模板中的模板变量是可行的,因为子模板会从父模板继承上下文

5)从外部的父模板访问本模板中的变量是行不通的

<ng-template [ngIf]="true">
  <!-- The reference is defined within a template -->
  <input #ref2 type="text" [(ngModel)]="secondExample" />
</ng-template>
<!-- ref2 accessed from outside that template doesn't work -->
<span>Value: {{ ref2?.value }}</span>

 

 posted on 2020-12-11 16:52  楼顶铁板烧  阅读(106)  评论(0编辑  收藏  举报