angular6.x中ngTemplateOutlet指令的使用

在使用angular進行開發的時候,經過屬性綁定向組件內部傳值的方式,有時候並不能徹底知足需求,好比咱們寫了一個公共組件,可是某個模板使用這個公共組件的時候,須要在其內部添加一些標籤內容,這種狀況下,除了使用ngIf/ngSwitch預先在組件內部定義以外,就能夠利用ngTemplateOutlet指令向組件傳入內容.vue

ngTemplateOutlet指令相似於angularjs中的ng-transclude,vuejs中的slot.angularjs

ngTemplateOutlet是結構型指令,須要綁定一個TemplateRef類型的實例.app

使用方式以下:this

@Component({
  selector: 'app',
  template: `
    <h1>Angular's template outlet and lifecycle example</h1>
    <app-content [templateRef]="nestedComponentRef"></app-content>
    <ng-template #nestedComponentRef let-name>
      <span>Hello {{name}}!</span>
      <app-nested-component></app-nested-component>
    </ng-template>
  `,
})
export class App {}
@Component({
  selector: 'app-content',
  template: `
    <button (click)="display = !display">Toggle content</button>
    <template 
        *ngIf="display" 
        *ngTemplateOutlet="templateRef context: myContext">
    </template>
  `,
})
export class Content {
  display = false;
  @Input() templateRef: TemplateRef;
  myContext = {$implicit: 'World', localSk: 'Svet'};
}
@Component({
  selector: 'app-nested-component',
  template: `
    <b>Hello World!</b>
  `,
})
export class NestedComponent implements OnDestroy, OnInit {
  
  ngOnInit() {
    alert('app-nested-component initialized!');
  }
  
  ngOnDestroy() {
    alert('app-nested-component destroyed!');
  }
  
}

代碼中除了根組件外定義了兩個組件spa

  • 容器組件:app-content
  • 傳遞進去的內容組件:app-nested-component

app-content組件接收一個TemplateRef類型的輸入屬性templateRef,並在模板中將其綁定到了ngTemplateOutlet指令,當組件接收到templateRef屬性時,就會將其渲染到ngTemplateOutlet指令所在的位置.code

上例中,app-content組件templateRef屬性的來源,是在根組件的模板內,直接經過#符號獲取到了app-nested-component組件所在<ng-template>的引用並傳入的.component

在實際應用中,除了這種方式,也能夠直接在組件內部獲取TemplateRef類型的屬性並綁定到ngTemplateOutlet指令.ci

好比在容器組件爲模態框的狀況下,並不能經過模板傳值,就能夠使用下面這種方式:開發

@ViewChild('temp') temp: TemplateRef<any>

 openDialog(){
   this.dialog.open(ViewDialogComponent, {data: this.temp)
 }

在容器組件中還能夠定義被傳遞內容的上下文(上例app-content組件中的myContext屬性),其中的$implicit屬性做爲默認值,在被傳遞的內容中能夠以重命名的方式訪問(上例let-name),對於上下文中其餘的屬性,就須要經過let-屬性名的方式訪問了.it

相關文章
相關標籤/搜索