本文介绍了如何在角度4、5中为动态元素分配哈希ID参考ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果我的问题很愚蠢,我有30多个静态ng-container,带有一些唯一的静态#hashtagID,但我想在ngFor的帮助下动态创建它们

I am sorry if my question was silly, i am having 30+ static ng-container with some unique static #hashtagID but i want to create them dynamically with help of ngFor

public lists = ['food', 'book', ........, 'cook']

期望输出:

<ng-container #food></ng-container>
<ng-container #book></ng-container>
..
..
<ng-container #cook></ng-container>

所以我几乎尝试了所有方法,但是没有运气,

So i tried almost all ways but no luck,

1: <ng-container *ngFor="#id of lists"><ng-container>
2: <ng-container *ngFor="let id of lists" #{{id}}><ng-container>
3: <ng-container *ngFor="let id of lists" #+"id"><ng-container>
4: <ng-container *ngFor="let id of lists" #{id}><ng-container>
5. <div *ngFor="let id of lists" #id></div>
6: <div *ngFor="let id of lists" [id]="id">

我正在将此#hashTagID用作.ts文件中的viewContainerRef.

i am using this #hashTagID as viewContainerRef in .ts file.

@ViewChild('food',{read:ViewContainerRef})私人食物:ViewContainerRef;

请有人帮助我解决此问题.

Please someone help me to resolve this issue.

推荐答案

可能的解决方案可能是创建一个指令,该指令将哈希作为输入并且还引用了ViewContainerRef:

Possible solution could be creating a directive that will take hash as input and also have reference to ViewContainerRef:

@Directive({
  selector: '[hash]',
})
export class HashDirective  {
  @Input() hash: string;

  constructor(public vcRef: ViewContainerRef) {}
}

现在您可以将模板编写为:

Now you can write template as:

<ng-container *ngFor="let item of lists" [hash]="item"></ng-container>

最后,您将能够通过ViewChildren引用所需的ViewContainerRef:

And finally you will be able to get reference to desired ViewContainerRef through ViewChildren:

@ViewChildren(HashDirective) private hashes: QueryList<HashDirective>;

lists = ['food', 'book', 'cook'];

getContainerFor(name: string) {
  return this.hashes.find(x => x.hash === name).vcRef;
}

ngAfterViewInit() {
  console.log(this.getContainerFor('food'));
}

示例

Example

这篇关于如何在角度4、5中为动态元素分配哈希ID参考ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:30