在 html 中动态命名 div 并使用 @ViewChild('xyz') div: ElementRef;在角度

Posted

技术标签:

【中文标题】在 html 中动态命名 div 并使用 @ViewChild(\'xyz\') div: ElementRef;在角度【英文标题】:dynamically name the div in html and access the same using @ViewChild('xyz') div: ElementRef; in angular在 html 中动态命名 div 并使用 @ViewChild('xyz') div: ElementRef;在角度 【发布时间】:2020-12-22 08:22:41 【问题描述】:

我想在 *ngfor 中创建一个 div 并为其分配一个动态 id 并使用 viewchild 和 elementRef 在组件中访问它我当前的 html 如下

<ng-container *ngFor="let consult of crap | keyvalue; let j = index; trackBy: trackByFn;">
     <td>
       <input  type="radio" name="radio-i" id="radio-i-j(click)="questBuild(consult)"/>
             <label class="sr-text" for="radio-i-j">consult.value.text</label>
               <ng-container *ngIf="consult.value.quest">
                  <div #questions></div>
                </ng-container>
          </td>
    </ng-container>

并在组件中访问它

  @ViewChild('questions') div: ElementRef;

f 那么有没有办法在 *ngFor 中动态命名#questions 并使用组件中的@viewchild 访问它

【问题讨论】:

【参考方案1】:

使用ViewChildren。 View Children 是一个 QueryList,其中包含所有元素。

@ViewChildren('question') questions:QueryList<ElementRef> 
//or is yer "questions" are components
@ViewChildren('question') questions:QueryList<ComponentName> 

你可以访问一个特定的元素

const question=this.questions.find((x,i)=>i==index)

【讨论】:

以上是关于在 html 中动态命名 div 并使用 @ViewChild('xyz') div: ElementRef;在角度的主要内容,如果未能解决你的问题,请参考以下文章

如何在动态元素上使用 preventDefault?

多个下拉列表的 xPath 命名映射

给div中动态添加节点并设置样式

在 Ruby 中动态定义命名类

在 CICS 中读取动态命名的平面文件

动态添加/删除输入字段并在单独的 div 中预览字段值