国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-19 12:35:38
字體:
來源:轉載
供稿:網友

ngContentOutlet指令介紹

ngContentOutlet指令與ngTemplateOutlet指令類似,都用于動態組件,不同的是,前者傳入的是一個Component,后者傳入的是一個TemplateRef。

首先看一下使用:

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

其中MyComponent是我們自定義的組件,該指令會自動創建組件工廠,并在ng-container中創建視圖。

實現組件位置交換

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

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

動態創建組件,并實現位置交換

我們先創建一個數組,用于存放上文創建的兩個組件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; }}

執行命令npm start在瀏覽器中可以看到如下效果:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 廊坊市| 柘荣县| 南川市| 左云县| 龙游县| 恭城| 汝南县| 福鼎市| 西平县| 墨竹工卡县| 浮山县| 都安| 恩施市| 茶陵县| 廉江市| 湘阴县| 桦川县| 云龙县| 金华市| 布拖县| 拜泉县| 广汉市| 正镶白旗| 盐源县| 海丰县| 江阴市| 邵东县| 邵武市| 封开县| 武夷山市| 临颍县| 信丰县| 屏东县| 深州市| 安乡县| 渝中区| 柏乡县| 兴城市| 建瓯市| 新乐市| 焉耆|