Angular2 - 事件和属性 - 02

我们在前面对时间和属性做了一些介绍。我们来看看其他的Angular绑定,在这里我们要提一些当Angular在进行绑定的时候。Angular会对绑定的内容做一次消毒处理。无论你是属性绑定还是插值表达式。

当我们想要帮下面的值绑定到DOM或者HTML中是。Angular会检查是否有恶意内容出现。

evilTitle = 'Template <script>alert("evil never sleeps")</script>Syntax';
<!--
  Angular generates warnings for these two lines as it sanitizes them
  WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
 -->
<p><span>"{{evilTitle}}" is the <i>interpolated</i> evil title.</span></p>
<p>"<span [innerHTML]="evilTitle"></span>" is the <i>property bound</i> evil title.</p>

我们可以看到页面上出现了警告。并且标签也被完全显示。并不会有提示出现。

  • [attr.colspan],attribute 绑定,当我们没有属性可以绑定的时候。我们就必须使用attribute来绑定数据,比如table,svg中的colspan或者rowspan等attribute。他们是attribute,没有对应的属性可以绑定。

我们尝试绑定colspan带上计算表达式。会得到错误:

<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>

//当我们像上面一样给colspan绑定表达式时,会得到如下错误结果。
//因为table没有colspan属性。但是Angular的插值表达式和属性绑定只能设置属性。不能设置attribute
Template parse errors: Can
't bind to 'colspan' since it isn't a known native property

所以Angular基于这一痛点给出了绑定规则。[attr.colspan],我们改变一下上面的语句来看看结果.

<table border="1">
   <tr>
      <td>test1</td>
      <td>test2</td>
   </tr>
      <tr>
      <td [attr.colspan]="1 + 1">test colspan</td>
   </tr>
</table>

这样td就colspan了两列了。。

attribute 绑定的主要用例之一是设置 ARIA attribute(译注:ARIA 指可访问性,用于给残障人士访问互联网提供便利), 就像这个例子中一样:

<!-- create and set an aria attribute for assistive technology -->
<button [attr.aria-label]="actionName">{{actionName}} with Aria</button>
  • css类绑定。前面一节我们提到了css的绑定语法。这里就不过多介绍了。
    • [class.special] = "expression"
    • [style.color] = "red"
    • [style.font-size.px] = "15px"

当我们想要根据变量来改变属性值的时候我们可以向下面一样操作。

//Component 定义变量delta , 修改delta的值。div的font-size也会想要更改。

<input [(ngModel)]="delta" type="text"/> <div [style.font-size.px]="delta">Resize Font</div>

 


但值得注意的是。即使你delta定义的是number内心。当在input里面修改delta的值之后会变成string类型。这就会有一个新的问题。当你想要和其他的number类型做加法运算的时候需要做类型转换。

  • x 和 xChange 事件。这就为我们在父子Component结构中传值和坚持x的改变提供了方便。当我们在一个ParentComponent中使用另一个ChildComponent,的时候,我们需要吧ParentComponent的值传入到ChildComponent中。做一系列的运算。在返回结果。
//在parent component我们调用了app-child component,并把fontSizePx以size作为变量传入app-child中。
<app-child [(size)] ="fontSizePx"></app-child> <div [style.font-size.px]="fontSizePx">Resizable Text</div>
import { Component, OnInit , Input , Output , EventEmitter} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.sass']
})
export class ChildComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  @Input() size: number; //接收size作为变量
  @Output() sizeChange = new EventEmitter<number>(); //暴露sizeChange 时间接口

  resize() {
    this.size++;
    this.sizeChange.emit(this.size); //通知parent component size的改变
  }
}

当我们调用resize 方法之后,我们发现parent-component的font-size在主键增大。 

 

posted @ 2018-12-20 15:42  Allen●J  阅读(243)  评论(0编辑  收藏  举报