gpt4 book ai didi

angular - ViewContainerRef 与 ngFor

转载 作者:行者123 更新时间:2023-12-02 02:40:16 25 4
gpt4 key购买 nike

什么更好?使用 ngFor 或 ViewContainerRef 动态创建组件?有什么区别?

例如,如果我有一个创建新元素的按钮,每次按下它都会生成一个新组件。

1) 第一个选项如下

items: number[] = [];

addItem() {
this.items.push(1);
}

<my-component *ngFor="let item of items"></my-component>

2)第二个选项

@ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;

index: number = 0;

componentsReferences = [];

constructor(private CFR: ComponentFactoryResolver) {
}

createComponent() {

let componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
let componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory);
let currentComponent = componentRef.instance;

currentComponent.selfRef = currentComponent;
currentComponent.index = ++this.index;

// prividing parent Component reference to get access to parent class methods
currentComponent.compInteraction = this;

// add reference for newly created component
this.componentsReferences.push(componentRef);
}

remove(index: number) {

if (this.VCR.length < 1)
return;

let componentRef = this.componentsReferences.filter(x => x.instance.index == index)[0];
let component: ChildComponent = <ChildComponent>componentRef.instance;

let vcrIndex: number = this.VCR.indexOf(componentRef)

// removing component from container
this.VCR.remove(vcrIndex);

this.componentsReferences = this.componentsReferences.filter(x => x.instance.index !== index);
}

第一个选项是迭代数组并通过带有 ngFor 的组件显示其内容的典型方法。第二个选项使用 ViewContainerRef 而不是 ngFor。在以下链接中可以看到一个示例。

https://stackblitz.com/edit/add-or-remove-dynamic-component?file=src%2Fapp%2Fparent%2Fparent.component.ts

https://stackblitz.com/edit/angular-jukjib

最佳答案

根据我的理解:

If you want to insert new component or template, you need to tell Angular where to put this element. And that's what ViewContainerRef is. It is A DOM element (container) where you can put your newly component as a sibling to this element.

*ngFor Directive in Angular. NgFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item. ... of users means that we'll be iterating over the users iterable that should be made available in our component

总而言之,如果你想插入一个新的组件或模板作为兄弟,你可以选择ViewContainerRef,如果你只是迭代数组或对象之类的东西并创建一个模板在同一个组件中,使用 ngFor

希望对您有所帮助。欢迎大家指正

关于angular - ViewContainerRef 与 ngFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60007254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com