angular6 利用 ngContentOutlet 實現組件位置交換(重排)

ngContentOutlet指令介紹

ngContentOutlet指令與 ngTemplateOutlet指令相似,都用於 動態組件,不一樣的是, 前者傳入的是一個 Component,後者傳入的是一個 TemplateRef

首先看一下使用:css

<ng-container *ngComponentOutlet="MyComponent"></ng-container>

其中MyComponent是咱們自定義的組件,該指令會自動建立組件工廠,並在ng-container中建立視圖。npm

實現組件位置交換

angular中視圖是和數據綁定的,它並不推薦咱們直接操做HTML DOM元素,並且推薦咱們經過操做數據的方式來改變組件視圖。數組


首先定義兩個組件:

button.component.ts瀏覽器

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-button',
  template: `<button>按鈕</button>`,
  styleUrls: ['./button.component.css']
})
export class ButtonComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

text.component.tsapp

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-text',
  template: `
  <label for="">{{textName}}</label>
  <input type="text">
  `,
  styleUrls: ['./text.component.css']
})
export class TextComponent implements OnInit {
  @Input() public textName = 'null';
  constructor() { }

  ngOnInit() {
  }

}

咱們在下面的代碼中,動態建立以上兩個組件,並實現位置交換功能。this

動態建立組件,並實現位置交換

咱們先建立一個數組,用於存放上文建立的兩個組件 ButtonComponentTextComponent,位置交換時,只須要調換組件在數組中的位置便可,代碼以下:
import { TextComponent } from './text/text.component';
import { ButtonComponent } from './button/button.component';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <ng-container *ngFor="let item of componentArr" >
    <ng-container *ngComponentOutlet="item"></ng-container>
  </ng-container>
  <br>
  <button (click)="swap()">swap</button>
`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public componentArr = [TextComponent, ButtonComponent];
  constructor() {
  }
  public swap() {
    const temp = this.componentArr[0];
    this.componentArr[0] = this.componentArr[1];
    this.componentArr[1] = temp;
  }
}

執行命令npm start在瀏覽器中能夠看到以下效果:spa

圖片描述

相關文章
相關標籤/搜索