[Angular 2] Order Dynamic Components Inside an Angular 2 ViewContainer
2024-10-16 20:44:28
By default, when you generate components, they will simply be added to the page in order, one after another. Angular 2 provides methods on the ViewContainer that allow you to reorder components once they’ve been created and provide the order that you want.
When you want to create a component and insert it at cetern position of the list. Then what you need to do is just pass in a second param, when you call 'createComponent()'.
import {Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, Input} from '@angular/core';
import {SimpleService} from "../../serivces/simple.service";
import {WidgetThree} from "../widgets/widget-three.component"; @Component({
moduleId: module.id,
selector: 'home',
templateUrl: 'home.component.html'
})
export class HomeComponent { @ViewChild('container', {
read: ViewContainerRef
}) container; constructor(private resolver: ComponentFactoryResolver, private simpleService: SimpleService) {
} ngAfterContentInit(){
const WidgetFactory = this.resolver.resolveComponentFactory(WidgetThree);
this.container.createComponent(WidgetFactory);
this.container.createComponent(WidgetFactory);
this.container.createComponent(WidgetFactory);
this.container.createComponent(WidgetFactory);
const comRef = this.container.createComponent(WidgetFactory); // return a componentRef
comRef.instance.message = "I am last"; // using componentRef's instance prop to access the component prop
comRef.instance.renderer.setElementStyle(
comRef.instance.input.nativeElement,
'color',
'red'
)
} onClick(){
const WidgetFactory = this.resolver.resolveComponentFactory(WidgetThree);
const comRef = this.container.createComponent(WidgetFactory, );
comRef.instance.message = "I am third";
} }
So when click a button, we wil call 'onClick()' method, which will create a new component and insert it at the third place in the list.
最新文章
- laravel安装
- DOM动画效果基础入门
- Mecanim的Avater
- Bootstrap系列 -- 25. 下拉菜单分割线
- Linux 解压命令tar的理解
- MySQL(六) —— 运算符和函数
- Doragon Kuesuto 1.0
- java中子类与基类变量间的赋值
- Android源码学习
- 用SNMP协议实现系统信息监控--Windows Server 2008
- pandas和re中正则表达式的意思
- 第三个Sprint ------第七天
- 变长编码表 ASCII代码等长编码
- cocos2dx 3.x(纯代码实现弹出对话框/提示框/警告框)
- 通过tarball形式安装HBASE Cluster(CDH5.0.2)——配置分布式集群中的YARN ResourceManager 的HA
- 后台维护常用SQL
- SpringBoot入门篇--热部署
- iOS Swift WisdomHUD 提示界面框架
- C#(.net)水印图片的生成
- 题解-python-CodeForces 227B
热门文章
- Steam即将正式加入人民币支付(转)
- Vs2015 win10虚拟机启动问题:无法设置UDP端口 解决方法 合集(转载)
- 前端架构:Angular与requirejs集成实践
- no symbol version for module_layout
- 在使用EF开发时候,遇到 using 语句中使用的类型必须可隐式转换为“System.IDisposable“ 这个问题。
- hip-hop初探
- gradle gradlew 的使用
- 在IT网站上少花些时间
- Physicals
- C++11显式虚函数重载