[Angular 2] Order Dynamic Components Inside an Angular 2 ViewContainer
Angular an order Dynamic Components inside
2023-09-14 09:00:53 时间
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, 2); 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.
相关文章
- Angular tsconfig.json 文件里的 paths 用途
- Angular SSR 应用的 SEO 实现一个例子 - meta 和 title 元素的赋值
- uat环境和生产环境的区别_angular 生产环境 相对路径无效
- An软件如何下载 Adobe Animate 一键安装--AN软件下载完整版
- angular框架发展史
- Angular 模块封装概念常见的错误理解
- 【Angular教程】-组件初识|8月更文挑战
- Angular 应用如何回退到之前曾经浏览过的页面
- 关于 Angular 工程文件 angular.json 里的 inlineCritical 属性
- Angular SSR 应用启动时的一些保护措施
- Angular 项目中 angular.json builder 字段的可选项介绍
- 基于豆瓣API+Angular开发的webApp