Angular2模板语法与常用指令简介-创新互联

一、模板语法简介

插值表达式

平武ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!
Hello `name`

等价于

模板表达式

1.属性绑定

1.1输入属性的值为常量

等价于

1.2输入属性的值为实例属性

等价于

2.事件绑定

等价于

模板引用变量

 
Pause

等价于

双向绑定

等价于

*与

2.*ngFor


最终转换为

  
        
常用指令简介

NgIf

   b">
     

NgSwitch

有时候需要根据不同的条件,渲染不同的元素,此时我们可以使用多个ngIf来实现。

    
    Var is A 
    Var is B 
    Var is something else

如果myVar的可选值多了一个'C',就得相应增加判断逻辑:

 
    Var is A
    Var is B
    Var is C
    
        Var is something else    
    

可以发现Var is something else的判断逻辑,会随着myVar 可选值的新增,变得越来越复杂。遇到这种情景,我们可以使用ngSwitch指令。

    
    Var is A
    Var is BVar is C
    Var is something else

NgStyle

NgStyle 让我们可以方便得通过 Angular 表达式,设置 DOM 元素的 CSS 属性。

  • 设置元素的背景颜色

  Use fixed yellow background
  • 设置元素的字体大小


                 red text     

NgStyle 支持通过键值对的形式设置 DOM 元素的样式:

  
     Uses fixed white text on blue background

注意到background-color需要使用单引号,而color不需要。这其中的原因是,ng-style要求的参数是一个Javascript对象,color是一个有效的key,而background-color不是一个有效的key,所以需要添加''

NgStyle 源码片段

@Directive({selector: '[ngStyle]'})
export class NgStyle implements DoCheck {  
    private _ngStyle: {[key: string]: string};  
    
    private _differ: KeyValueDiffer;  
    
    constructor(    private _differs: KeyValueDiffers,     
        private _ngEl: ElementRef, private _renderer: Renderer) {}  
        
    @Input()  set ngStyle(v: {[key: string]: string}) {     
        //     
        this._ngStyle = v;    if (!this._differ && v) {     
          this._differ = this._differs.find(v).create();   
           } 
         }   
         
         // 设置元素的样式  private _setStyle(nameAndUnit: string, 
         value: string|number): void {    
         const [name, unit] = nameAndUnit.split('.'); 
         // 截取样式名和单位    
         value = value != null && unit ? `${value}${unit}` : value;  
         this._renderer.setElementStyle(this._ngEl.nativeElement, name, 
             value as string); 
     }
}

NgClass

NgClass 接收一个对象字面量,对象的key是 CSS class 的名称,value的值是truthy/falsy的值,表示是否应用该样式。

  • CSS Class

.bordered {    border: 1px dashed black; background-color: #eee;}
  • HTML



    This is never bordered



    This is always bordered



 
    Using object literal. Border {{ isBordered ? "ON" : "OFF" }}




    Class names contains dashes must use single quote




    This will always have a blue background and round corners

NgFor

NgFor 指令用来根据集合(数组) ,创建DOM元素,类似于ng1ng-repeat指令

 
  {{ num+1 }} - {{ c }}

使用trackBy提高列表的性能

@Component({  
    selector: 'my-app', 
    template: `
    
                  `item`.`id`               
         Refresh items  `,}) export class App {       constructor() {             this.collection = [             {id: 1},              {id: 2},              {id: 3}          ];       }           getItems() {             this.collection = this.getItemsFromServer();      }              getItemsFromServer() {          return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];       }              trackByFn(index, item) {             return index; // or item.id       } }

NgNonBindable

ngNonBindable 指令用于告诉 Angular 编译器,无需编译页面中某个特定的HTML代码片段。

 
    {{ content }}
    
        ← This is what {{ content }} rendered    
    

注意事项

1.使用[hidden]属性控制元素的可见性

  Hello, there!

上面的代码在通常情况下,都能正常工作。但当在对应的 DOM 元素上设置display: flex属性时,尽管[hidden]对应的表达式为true,但元素却能正常显示。对于这种特殊情况,则推荐使用*ngIf

2.直接使用DOMAPI 获取页面上的元素

@Component({  
    selector: 'my-comp',
    template: `
         
        
 Some other content 
  `}) export class MyComp {       constructor(el: ElementRef) {             el.nativeElement.querySelector('input').focus();      } }

以上的代码直接通过querySelector()获取页面中的元素,通常不推荐使用这种方式。更好的方案是使用@ViewChild和模板变量,具体示例如下:

@Component({  
    selector: 'my-comp', 
    template: `
        
        
 Some other content 
   `}) export class MyComp implements AfterViewInit {       @ViewChild('myInput') input: ElementRef;            constructor(private renderer: Renderer) {}              ngAfterViewInit() {              this.renderer.invokeElementMethod(             this.input.nativeElement, 'focus');          } }

另外值得注意的是,@ViewChild()属性装饰器,还支持设置返回对象的类型,具体使用方式如下:

@ViewChild('myInput') 
myInput1: ElementRef;

@ViewChild('myInput', {read: ViewContainerRef})
myInput2: ViewContainerRef;

若未设置read属性,则默认返回的是ElementRef对象实例。

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


当前标题:Angular2模板语法与常用指令简介-创新互联
文章来源:http://bzwzjz.com/article/dopdde.html