【问题标题】: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 访问它

【问题讨论】:

    标签: angular


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 2018-12-02
      • 1970-01-01
      • 2018-11-28
      • 2021-03-11
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多