AngularJS2初学小结

前端之家收集整理的这篇文章主要介绍了AngularJS2初学小结前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文的实例中用到了ng2-bootStrap,是用Angular2和bootStrap开发的第三方Component。感兴趣的同学可以戳链接看看。

###Component

  1. 自定义Component -在Angular2中使用@Component 注解在自定义组件:
import {Component} from '@angular/core';
import {AlertComponent,DATEPICKER_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
  selector: 'my-app',directives: [AlertComponent],templateUrl:'Demo.html'
})
export class AppComponent {
}

其中Demo.html就是一个html文件内容如下:

<alert type="info">ng2-bootstrap hello world!</alert>

你就可以在你的index.html中使用

截图如下:

2.@Component 的属性 在@Component中有几个比较常用的属性,上面的eg中出现了三个。

  • selector 相当与html的标签
  • directives 在你的Component 中使用到其他Component的类名。(在上eg.中我们使用到了ng2-bootstrap的<alert></alert>标签,他的类名为AlertComponent)
  • templateUrl 自定义的组件的html元素。

当然还有一些其他的常用属性,现在几个我比较常用的几个属性

3.inputs 和 outputs

  • inputs :此处的input和html的<input></input> 没有半毛钱关系自定义组件的某个值作为一个input,希望有上级组件为其赋值。 usage:
import {Component} from '@angular/core';
import {AlertComponent,DATEPICKER_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
  selector: 'demo',inputs: ['h2Value'],template: `
    <h2>{{h2Value}}</h2>
  `
})
export class InputComponent {
  public h2Value: string = "Hello";
}
@Component({
  selector: 'my-app',directives: [InputComponent],template: `
  <div>
  <demo [h2Value]="customValue"></demo>
  </div>
  `
})
export class AppComponent {
  customValue: string = "Hello World!";
}

可以看到在第一个Component中

的innerHTML为h2Value 是一个input,在AppComponent我们引用了他,故[h2Value]可以当做 标签中一个属性,并将其复制为customValue,为了与正常的html属性区别开,angular2将放在[]中。

猜你在找的Angularjs相关文章