angular6 利用 ngContentOutlet 實現組件位置交換

這篇文章主要介紹了angular6 利用 ngContentOutlet 實現組件位置交換(重排),小編以爲挺不錯的,如今分享給你們,也給你們作個參考。一塊兒跟隨小編過來看看吧css

ngContentOutlet指令介紹數組

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

首先看一下使用:this

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

實現組件位置交換component

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

首先定義兩個組件:it

button.component.tsclass

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.tsangular

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() {
 }
}

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

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

咱們先建立一個數組,用於存放上文建立的兩個組件ButtonComponent和TextComponent,位置交換時,只須要調換組件在數組中的位置便可,代碼以下:

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;
 }
}
相關文章
相關標籤/搜索