angular6如何使用ngContentOutlet实现组件位置交换(代码示例)

本篇文章给大家带来的内容是关于angular6如何使用ngcontentoutlet实现组件位置交换(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

ngContentOutlet指令介绍

ngContentOutlet指令与ngTemplateOutlet指令类似,都用于动态组件,不同的是,前者传入的是一个Component,后者传入的是一个TemplateRef。

首先看一下使用:

其中MyComponent是我们自定义的组件,该指令会自动创建组件工厂,并在ng-container中创建视图。

实现组件位置交换

angular中视图是和数据绑定的,它并不推荐我们直接操作HTML DOM元素,而且推荐我们通过操作数据的方式来改变组件视图。

首先定义两个组件:

button.component.ts

import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-button', template: ``, 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: `   `, 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: `     
`, 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; }}

登录后复制

以上就是angular6如何使用ngContentOutlet实现组件位置交换(代码示例)的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2736482.html

(0)
上一篇 2025年3月8日 01:25:02
下一篇 2025年3月8日 01:25:07

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论