angular2 笔记

动态添加一个component:

  

import {
   ViewContainerRef,
   Component,
   ComponentFactoryResolver,
   ViewChild
    } from '@angular/core';
import {InstanceComponent} from ' ./ instance.component';

@Component{
    selector:'my-app'
    template:`
      <div #insert> 
           insert Component
       </div>
    `
}
    
export class AppComponent{
  @ViewChild('insert',{read:ViewContainerRef})insert;
  constructor(
       private _vcr:ViewContainerRef       
       private _cfr:ComponentFactoryResolver  
 ){}
  ngAfterViewInit(){
      let factory=this._cfr.resolveComponentFactory(InstanceComponent); //先转换成factoryComponent类型。
      this._vcr.createComponent(factory);            // 在本component末尾加入factory;
       //或者this.insert.createComponent(factory);   // 在#insert内部的末尾加入factory;
  }
 clear(){
    this._cfr.clear()    //清除加入的元素。
  }
  remove(){                   //既然有加入component,那么也得写一个删除的方法。
     let node=this.insert.nativeElement;
     node.parentNode.removeChild(node);
   }

}

angular中的NgModule中存在entryComponents属性,一般是不需要配置的。因为被bootStrap直接及递归引导的component和router中定义的component,会被自动添加入entryComponent。

可是我们要加入的这个component,就没有落脚之地,所以你需要自己在app.module中的entryComponents里加入这个component。

下面是一些API: 

一,

@ViewChild:

   @ViewChild('insert',{read:_params});

_params:默认值为ElementRef;另一个可选值为ViewContainer;

@ViewChildren:

   在@ViewChild中填入component,难免该component不止被使用一次。所以在多次出现时,使用viewChildren;

@ContentChild:

  首先你得分清content与view的差别。他们所对应的元素,view是在native element中定义,content是在host element中定义再映射入native中。

@ContentChild(component) ;获得projection component;

@ContentChildren:

  相对于ContentChild选择多个。

使用进阶:

@Directive({
   selector:'div',
})export class myDirective{
    constructor(
       private el:ElementRef;  
    ){}
}

@Component ({
  template:`
      <div > one</div>
      <div> two </div>
   `
})export class AppComponent{
  @ViewChildren(myDirective)_md;
  ngAfterView(){
      this._md.map(node=>{
         console.log(node.el.nativeElement.nodeName); 
      });
    this._md.changes.subscribe(val=>{.....});

   }
}

@ViewChildren返回一个:QueryList。拥有map方法,但它不属于Array。

 myDirective将<div>绑定为一个Directive,并使其具有.el属性。其中第一个div多带一个id属性。注意,不做injector或者attr,将返回一个空的{}。

 this._md.changes可以监听这些ViewChildren的变化,比如add,move,remove. 

@ContentChildren。使用方法雷同。

二,动态 innerHTML。

ViewContainerRef.createEmbeddedView

@Component ({
   template:`
     <template #tp>
         <h1> templateRef</h1>
     </template>
             `

})export class AppComponent{
   @ViewChild('tp')tp;
   constructor(private _vcr:ViewContainerRef){};
   ngAfterViewInit(){
       
        this._vcr.createEmbeddedView(tp);
    }


}

 @ViewChild('tp')得到的是一个templateRef;

通过这个方法,可以达成类似Jquery 中,$('<h1> templateRef</h1>').insertAfter('my-app')的效果。

三,私有注入。

  ViewProviders:[];

  angular中除了惰性模块,一旦你使用providers注册服务,那它会立即提升为全局。

   所以在一些特殊情况需要私有服务时,我们使用ViewProviders代替providers,因为ViewProviders内的服务,只能被自身及ViewChildren使用。

------------这个排版不好用啊。有时间自己搞几个class。。。- -!