angular6 利用 ngContentOutlet 實(shí)現(xiàn)組件位置交換(重排)
ngContentOutlet指令介紹
ngContentOutlet指令與ngTemplateOutlet指令類(lèi)似,都用于動(dòng)態(tài)組件,不同的是,前者傳入的是一個(gè)Component,后者傳入的是一個(gè)TemplateRef。
首先看一下使用:
<ng-container *ngComponentOutlet="MyComponent"></ng-container>
其中MyComponent是我們自定義的組件,該指令會(huì)自動(dòng)創(chuàng)建組件工廠(chǎng),并在ng-container中創(chuàng)建視圖。
實(shí)現(xiàn)組件位置交換
angular中視圖是和數(shù)據(jù)綁定的,它并不推薦我們直接操作HTML DOM元素,而且推薦我們通過(guò)操作數(shù)據(jù)的方式來(lái)改變組件視圖。
首先定義兩個(gè)組件:
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.ts
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() { } }
我們?cè)谙旅娴拇a中,動(dòng)態(tài)創(chuàng)建以上兩個(gè)組件,并實(shí)現(xiàn)位置交換功能。
動(dòng)態(tài)創(chuàng)建組件,并實(shí)現(xiàn)位置交換
我們先創(chuàng)建一個(gè)數(shù)組,用于存放上文創(chuàng)建的兩個(gè)組件ButtonComponent和TextComponent,位置交換時(shí),只需要調(diào)換組件在數(shù)組中的位置即可,代碼如下:
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; } }
執(zhí)行命令npm start在瀏覽器中可以看到如下效果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Angular引入swiper后autoplay失效的解決辦法詳解
這篇文章主要介紹了Angular引入swiper后autoplay失效的解決辦法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09AngularJS+Bootstrap3多級(jí)導(dǎo)航菜單的實(shí)現(xiàn)代碼
將介紹如何用AngularJS構(gòu)建一個(gè)強(qiáng)大的web前端系統(tǒng)。文章介紹如何實(shí)現(xiàn)多限級(jí)導(dǎo)航菜單。本文圖文并茂給大家介紹的非常詳細(xì),感興趣的朋友參考下吧2017-08-08Angular中實(shí)現(xiàn)樹(shù)形結(jié)構(gòu)視圖實(shí)例代碼
近兩年當(dāng)中使用Angular開(kāi)發(fā)過(guò)很多項(xiàng)目,其中也涉及到一些樹(shù)形結(jié)構(gòu)視圖的顯示,最近的在項(xiàng)目中封裝了大量的組件,一些組件也有樹(shù)形結(jié)構(gòu)的展示,所以寫(xiě)出來(lái)總結(jié)一下。2017-05-05AngularJS 過(guò)濾與排序詳解及實(shí)例代碼
這篇文章主要介紹了AngularJS 過(guò)濾與排序,這里整理了詳細(xì)的資料及簡(jiǎn)單實(shí)例代碼,有需要的小伙伴可以參考下2016-09-09AngularJS實(shí)現(xiàn)使用路由切換視圖的方法
這篇文章主要介紹了AngularJS實(shí)現(xiàn)使用路由切換視圖的方法,結(jié)合學(xué)生信息管理系統(tǒng)為例分析了使用controllers.js控制器來(lái)切換視圖的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-01-01