小編給大家分享一下angular6使用ngContentOutlet實(shí)現(xiàn)組件位置交換的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
成都創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括武陵源網(wǎng)站建設(shè)、武陵源網(wǎng)站制作、武陵源網(wǎng)頁(yè)制作以及武陵源網(wǎng)絡(luò)營(yíng)銷策劃等。多年來(lái),我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,武陵源網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到武陵源省份的部分城市,未來(lái)相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
ngContentOutlet指令介紹
ngContentOutlet指令與ngTemplateOutlet指令類似,都用于動(dòng)態(tài)組件,不同的是,前者傳入的是一個(gè)Component,后者傳入的是一個(gè)TemplateRef。
首先看一下使用:
其中MyComponent是我們自定義的組件,該指令會(huì)自動(dòng)創(chuà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; } }
看完了這篇文章,相信你對(duì)angular6使用ngContentOutlet實(shí)現(xiàn)組件位置交換的方法有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
網(wǎng)站名稱:angular6使用ngContentOutlet實(shí)現(xiàn)組件位置交換的方法
當(dāng)前地址:http://chinadenli.net/article18/ppesdp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開(kāi)發(fā)、用戶體驗(yàn)、定制開(kāi)發(fā)、Google、品牌網(wǎng)站建設(shè)、網(wǎng)站營(yíng)銷
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)