Angular中动态创建组件

动态创建组件

通常来说组件不需要动态来创建,因为直接在模板中使用可以满足大部分的需求。可是如果有这样的需求
模板中存在多个组件是否显示依赖特定的条件,那么就需要定义多个bool类型的变量来控制,而且还需要考虑bool类型变量
的修改,这样操作起来比较繁琐。这个时候可以考虑使用动态创建组件的方式。大致流程如下所示。

创建组件

@Component({
  template: `<span>hello world</span>`
})
export class DynamicComponent { }

创建容器组件

@Component({
  selector: 'app-container',
  template: `
    <div #dynamicContainer></div>
    <button (click)="createComponent()">Create</button>
  `
})
export class AppContainerComponent {
  @ViewChild("dynamicContainer", { read: ViewContainerRef }) container: ViewContainerRef;
}

在AppContainerComponent组件中,通过@ViewChild装饰器来获取视图中的模板元素,如果没有指定第二个查询参数,则默认返回
组件实例或相应的DOM元素,但这个示例中,我们需要获取ViewContainerRef实例也就是视图容器。可以在视图容器中创建、插入、删除组

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个Angular动态组件示例,该组件可以根据输入的组件类型动态创建并显示组件: app.component.ts ``` import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'app-root', template: ` <div #container></div> <button (click)="createComponent('dynamic')">Create Dynamic Component</button> `, }) export class AppComponent { @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver) {} createComponent(type: string) { // 根据组件类型获取组件工厂 const factory = this.resolver.resolveComponentFactory(DynamicComponent); // 创建组件实例 const componentRef = this.container.createComponent(factory); // 设置组件属性 componentRef.instance.type = type; } } ``` dynamic.component.ts ``` import { Component, Input } from '@angular/core'; @Component({ selector: 'app-dynamic', template: ` <div *ngIf="type"> Dynamic Component Type: {{ type }} </div> `, }) export class DynamicComponent { @Input() type: string; } ``` 在这个例子,我们首先在`AppComponent`使用`ViewChild`获取了一个`ViewContainerRef`引用,这个`ViewContainerRef`表示了一个可以动态添加组件的容器。然后,我们在`createComponent`方法根据输入的组件类型获取了一个组件工厂,并使用`createComponent`方法创建了一个组件实例,并将其添加到了容器。最后,我们还在`DynamicComponent`添加了一个`Input`属性`type`,用于接收传递进来的组件类型。 使用这个动态组件的示例可以参考以下内容: ``` <app-root></app-root> ``` 在页面添加了一个按钮,当点击按钮时,会调用`AppComponent`的`createComponent`方法创建一个`DynamicComponent`实例,并将其添加到页面的容器。这个`DynamicComponent`实例会根据传递进来的组件类型显示不同的内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值